'Cypress unable to find selector - React/CSS Modules/Cypress

I am writing e-2-e tests for our frontend using Cypress.

When I try to target an element, I am using .button-module_btnLabel__30kQb, but as I understand this makes my test brittle as the classname hash may change.

However, when I try to add a selector, Cypress can't find it. An example below:

import { Button } from '...ui'
      <Button.Primary
        data-cy="submit"
        onClick={startLogin}
      >
        Log In
      </Button.Primary>
      cy.get('data-cy="submit"')
      .should('be.visible')
      .should('contain.text','Log In')
      .click()
     AssertionError: Timed out retrying after 4000ms: Expected to find element: `[data-cy=submit]`, but never found it.


Solution 1:[1]

If you are selecting on an attribute, you need enclosing square brackets.

cy.get('[data-cy="submit"]')

Note React does not pass on all attributes, but data prefix should be ok.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fody