Search code examples
csstestingintegration-testingcypress

Cypress testing pseudo CSS class :before


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?


Solution

  • 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-"')
    })