...

/

Dom Elements Selection: Cypress-testing-library

Dom Elements Selection: Cypress-testing-library

Let's learn about Cypress-testing-library.

Testing-library

Testing Library by Kent C. Dodds is based on the assumption that tests must consume the web app the same way a consumer does.

What does this mean? Well, try thinking about how users consume a web app. They interact with contents, labels, placeholders, buttons. Users do not care about the selectors, but about ** contents**. Accordingly, if the users cannot find these elements then they cannot use the application as intended. As a developer, this means you have a UX problem. By testing from the user perspective, you can avoid these problems early before your web page goes live and impacts users.

Take a look at this test:

Press + to interact
context("Signup flow", () => {
it("The happy path should work", () => {
cy.visit("/register");
const random = Math.floor(Math.random() * 100000);
cy.get("[data-testid=username]").type(`Tester${random}`);
cy.get("[data-testid=email]").type(`user+${random}@realworld.io`);
cy.get("[data-testid=password]").type("mysupersecretpassword");
cy.get("[data-testid=signup-button]").click();
cy.get("[data-testid=no-articles-here]", { timeout: 10000 }).should("be.visible");
});
});

Input fields that respond to the [data-testid=username] selector do not give us confidence that a user can easily consume our content, nor that the right element has the data-testid attribute.

The Testing Library has many plugins, one of which is dedicated to Cypress.

Using the testing library, we can leverage all the Testing Library functions, like findByText, findByPlaceholderText ...