本文介绍了赛普拉斯测试伪CSS类:之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在Cypress元素上测试伪CSS类的 content ?

我看到了链接记录:

但是我没有使用 :: before 伪类为CSS类找到任何东西.

想象一下代码:

  .myClass:before {内容:"foo-";}  
 < div>< span class ="myClass"> Bar</span></div>  

如何测试"foo-"的存在?

解决方案

有一种方法可以对伪元素的CSS属性进行断言,尽管它并不像使用赛普拉斯命令那样简单.

  1. 使用 cy.get()获取对该元素的引用.
  2. 从元素上读取 Window 对象,然后调用 Window.getComputedStyle(),它可以读取计算出的伪选择器的CSS.
  3. 使用 getPropertyValue 在返回的CSS声明中读取 content 属性的值.
  4. 声明.

下面是一个示例,该示例适用于OP中发布的代码:

  cy.get('.myClass').then($ els => {//从元素获取Window引用const win = $ els [0] .ownerDocument.defaultView//使用getComputedStyle读取伪选择器const before = win.getComputedStyle($ els [0],'before')//读取`content` CSS属性的值const contentValue = before.getPropertyValue('content')//返回的值将用双引号引起来,但这是正确的Expect(contentValue).to.eq('"foo-"')}) 

Is there a way in which I can test the content of the pseudo CSS class for :before on my element with Cypress?

I have seen links documenting:

But I have not found anything for CSS classes using the ::before pseudo class.

Imagine the code:

.myClass:before {
  content: "foo-";
}
<div>
  <span class="myClass">Bar</span>
</div>

How could one test that 'foo-' is present?

解决方案

There's a way to assert on the CSS properties of pseudo-elements, although it's not as simple as just using a Cypress command.

  1. Use cy.get() to get a reference to the element.
  2. Read the Window object off of the element, and then invoke Window.getComputedStyle(), which can read the computed CSS of pseudo selectors.
  3. Use getPropertyValue on the returned CSS declaration to read the value of the content property.
  4. Assert on it.

Here's an example that works on the code posted in the OP:

cy.get('.myClass')
.then($els => {
  // get Window reference from element
  const win = $els[0].ownerDocument.defaultView
  // use getComputedStyle to read the pseudo selector
  const before = win.getComputedStyle($els[0], 'before')
  // read the value of the `content` CSS property
  const contentValue = before.getPropertyValue('content')
  // the returned value will have double quotes around it, but this is correct
  expect(contentValue).to.eq('"foo-"')
})

这篇关于赛普拉斯测试伪CSS类:之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 23:15