简体   繁体   中英

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.

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()

Custom commmands commands.js

Cypress.Commands.add("sendBtn", () => {
  cy.get("[data-cy=cy_send_btn]")
   .should("be.visible")
   .click()
})

And in test file

it("Add test description here", function() {
  .
  . 
  .
  .
  cy.sendBtn()
})

Custom command shown above you will be able to use multiple times in other test files for all send buttons. Your tests will be more isolated and efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM