phy*_*boy 3 css testing integration-testing cypress
有没有一种方法可以content通过Cypress在元素上测试:CSS的伪CSS类?
我看过链接记录:
但是我没有使用::before伪类为CSS类找到任何东西。
想象一下代码:
.myClass:before {
content: "foo-";
}Run Code Online (Sandbox Code Playgroud)
<div>
<span class="myClass">Bar</span>
</div>Run Code Online (Sandbox Code Playgroud)
如何测试“ foo-”的存在?
基于Zach 的回答,我创建了一个返回伪元素属性的命令(周围没有单引号)。
function unquote(str) {
return str.replace(/(^")|("$)/g, '');
}
Cypress.Commands.add(
'before',
{
prevSubject: 'element',
},
(el, property) => {
const win = el[0].ownerDocument.defaultView;
const before = win.getComputedStyle(el[0], 'before');
return unquote(before.getPropertyValue(property));
},
);
Run Code Online (Sandbox Code Playgroud)
你会像这样使用它
it('color is black', () => {
cy.get('button')
.before('color')
.should('eq', 'rgb(0,0,0)'); // Or .then()
});
Run Code Online (Sandbox Code Playgroud)
有一种方法可以对伪元素的CSS属性进行断言,尽管它不像使用Cypress命令那样简单。
cy.get()获得的元素的引用。Window从元素上读取对象,然后调用Window.getComputedStyle(),它可以读取计算出的伪选择器的CSS。getPropertyValue返回的CSS声明以读取content属性的值。这是一个适用于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-"')
})
Run Code Online (Sandbox Code Playgroud)