Search⌘ K

Dom Elements Selection: Cypress-testing-library

Explore how to use Cypress Testing Library to select DOM elements in ways that reflect actual user interactions. Learn techniques to write readable tests that focus on content and labels over selectors, making debugging easier and tests more stable. Understand how to handle multiple elements with the same text and improve test feedback to identify UX issues early.

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:

C++
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, ...