Search code examples
sasshovercypress

How do I test a button for focus and hover (screenshot/&::after)?


It seems that I cannot find a correct way of doing this in Cypress.

I want to test my buttons for hover and focus state.

First thing I tried was to take a screenshot of the whole component not just the buttons with cypress-image-snapshot when I use realhover on a element, but that doesn't seems to work.

Second thing I tried was via css but that also doesn't work because, when the element is in focus the background color of my &::after is changed via a scss variable, which I cannot get via cypress.

Has anyone any idea or has a solution for testing these states ?


Solution

  • I wouldn't go down the route of screenshots, rather test the element css when hovering.

    But .realHover() from cypress-real-events is the easiest way to set up the test condition.

    cy.get('a[href="https://www.w3schools.com"]')
      .realHover()
      .then($el => {
        return window.getComputedStyle($el[0], ':after')  // pass pseudo in a 2nd parameter
          .getPropertyValue('background-color')
      })
      .should('eq', 'rgb(255, 255, 0)')  // ✅ passes
    

    Tested with this page

    <html>
      <head>
        <style>
          :hover {
            --backgroundColor: yellow;
          }
    
          a::after {
            background-color: var(--backgroundColor);
          }
        </style>
      </head>
      <body>
        <h1>Demo of the :hover selector</h1>
        <p>The :hover selector style links on mouse-over:</p>
        <a href="https://www.w3schools.com">w3schools.com</a>
        <a href="https://www.wikipedia.org">wikipedia.org</a>
      </body>
    </html>
    

    Comment out the .realHover() and the result is rgb(0, 0, 0).


    SCSS

    Forget about the SCSS variable, it is compiled away when the page is served.

    Cypress tests only see the resulting CSS.

    enter image description here