Search code examples
reactjsseleniumtestingcypressintegration-testing

Testing workflow with Cypress and React


I have question regarding the development and testing workflow. I am using Cypress but this topic is suitable for any end to end test.

The question is how do you selecting the elements in the browser?

1, Explicit selectors like data-cy or automation-id on each element or component.

2, Selecting the elements by visible text on the screen and then navigate to specific element by DOM hierarchy.


Solution

  • Every test you write will include selectors for elements. To save yourself a lot of headaches, you should write selectors that are resilient to changes.

    Oftentimes we see users run into problems targeting their elements because:

    Your application may use dynamic classes or ID's that change Your selectors break from development changes to CSS styles or JS behavior Luckily, it is possible to avoid both of these problems.

    Don't target elements based on CSS attributes such as: id, class, tag Don't target elements that may change their textContent Add data-* attributes to make it easier to target elements

    <button
      id="main"
      class="btn btn-large"
      name="submission"
      role="button"
      data-cy="submit"
    >
      Submit
    </button>
    

    And then for example clicking to button

    cy.get("[data-cy=submit]")
    .should("be.visible")
    .click()
    

    You can also search for specific text in dom.

    cy.get("button")
    .should("be.visible")
    .contains("Submit")
    .click()