Cypress 测试伪 CSS class :before

Cypress testing pseudo CSS class :before

有没有一种方法可以让我用 Cypress 在我的元素上测试 :before 的伪 CSS class 的 content

我看到链接记录:

但我还没有找到 CSS classes 使用 ::before 伪 class.

的任何内容

想象一下代码:

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

如何测试 'foo-' 是否存在?

有一种方法可以断言伪元素的 CSS 属性,尽管它不像使用 Cypress 命令那么简单。

  1. 使用 cy.get() 获取元素的引用。
  2. 从元素中读取 Window 对象,然后调用 Window.getComputedStyle(), which can read the computed CSS of pseudo selectors.
  3. 在返回的 CSS 声明中使用 getPropertyValue 来读取 content 属性.
  4. 的值
  5. 断言它。

这是一个适用于 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-"')
})

尝试断言父文本:

cy.get('.myClass').parent().should('have.text', 'foo-bar')

如果这不起作用,您可能必须使用 textContent 属性:

cy.get('.myClass').parent(). should($el => expect ($el).to.contain('foo-bar')
)

基于我创建了一个命令returns伪元素属性(周围没有单引号)。

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));
    },
);

你会这样使用它

it('color is black', () => {
    cy.get('button')
       .before('color')
       .should('eq', 'rgb(0,0,0)'); // Or .then()
});

这是我获取、转换和比较十六进制 background-color 与返回的 rgb 的解决方案。

const RGBToHex = (rgbColor) => {
  // it parse rgb(255, 13, 200) to #fa92D4
  const [red, green, blue] = rgbColor.replace(/[a-z]|\(|\)|\s/g, '').split(',');
  let r = parseInt(red, 10).toString(16);
  let g = parseInt(green, 10).toString(16);
  let b = parseInt(blue, 10).toString(16);

  if (r.length === 1) r = `0${r}`;
  if (g.length === 1) g = `0${g}`;
  if (b.length === 1) b = `0${b}`;

  return `#${r}${g}${b}`;
};


cy.get('.element').then(($el) => {
  const win = $el[0].ownerDocument.defaultView;
  const before = win.getComputedStyle($el[0], 'before');
  const bgColor = before.getPropertyValue('background-color');
  expect(RGBToHex(bgColor)).to.eq('#HEXA');
});