4

I'm currently working on a large project that uses many custom React components that I do not control. So it's not an option for me to modify them, and it's infeasible for me to make a pull request for every single custom component that doesn't have the behavior that I want.

I'm seeking to use Cypress to interact with these components. However, these custom components don't seem to support the use of data-* or id props. The text of these components could change depending upon the language the user is using.

The only way I see that you're able to get elements in Cypress is by finding what classes are assigned to them and selecting based upon the class value.

Cypress documentation says that you should never do this as it's likely to change, and it is.

However, I've been trying to find alternative solutions but have not been able to find any other solutions.

Is there a good way to force a the outermost html element of a react component that you don't control to take on an data-* or id attribute, or any other solution that can be used for robust Cypress testing?

1 Answers1

5

you can easily access react components using cypress-react-selector. It uses react's internal properties like component, props, and states to identify the element in real-time. You don't need to set any custom attribute in your JSX, you can find out the elements in a way which more native to REACT.

  • Install the library as dependency
npm i -D cypress-react-selector
  • Update Cypress/support/index.js file to include the cypress-react-selector commands by adding:
import 'cypress-react-selector';
  • user react-selector in your test like:
describe('It should validate cypress react selector', () => {
  before(() => {
    cy.visit('https://ahfarmer.github.io/calculator/');
    cy.waitForReact();
  });

  it('it should validate react selection with wildcard', () => {
    cy.react('*', { name: '9' }).should('have.text', '9');
  });

  it('it should validate react chaining', () => {
    cy.react('t', { name: '5' }).react('button').should('have.text', '5');
  });

});

It has a lot more functionalities to offer. Follow the instructions in the readme.

Here is a live example of handling react formik forms using cypress-react-selector.

Abhinaba
  • 376
  • 1
  • 8