0
0
Cypresstesting~5 mins

cypress-testing-library

Choose your learning style9 modes available
Introduction

cypress-testing-library helps you find and interact with web page elements like a user would. It makes tests easier to write and understand.

When you want to test a button by its label text instead of a complex selector.
When you need to check if a heading or paragraph with specific text is visible on the page.
When you want to simulate user actions like clicking or typing in a way that matches real user behavior.
When you want your tests to be more readable and less tied to the page's HTML structure.
When you want to avoid brittle tests that break when the page layout changes but the user experience stays the same.
Syntax
Cypress
import '@testing-library/cypress/add-commands';

// Example usage in a test
cy.getByRole('button', { name: 'Submit' }).click();

Use getByRole to find elements by their role and accessible name, which matches how users see the page.

Import @testing-library/cypress/add-commands to extend Cypress with user-friendly selectors.

Examples
Finds an element with the exact text 'Login' and clicks it.
Cypress
cy.getByText('Login').click();
Finds an input box labeled 'Username' and types 'myuser' into it.
Cypress
cy.getByRole('textbox', { name: 'Username' }).type('myuser');
Checks that the input labeled 'Email' is visible on the page.
Cypress
cy.getByLabelText('Email').should('be.visible');
Sample Program

This test visits a login page, fills in username and password using labels, clicks the login button by its role and name, then checks if a welcome message appears.

Cypress
import '@testing-library/cypress/add-commands';

describe('Login form test', () => {
  it('should allow user to login', () => {
    cy.visit('https://example.com/login');
    cy.getByLabelText('Username').type('testuser');
    cy.getByLabelText('Password').type('password123');
    cy.getByRole('button', { name: 'Log In' }).click();
    cy.getByText('Welcome, testuser!').should('be.visible');
  });
});
OutputSuccess
Important Notes

Always import @testing-library/cypress/add-commands once to enable the commands.

Using roles and labels makes tests more accessible and closer to how real users find elements.

These selectors are less likely to break if the page layout changes but the user interface stays the same.

Summary

cypress-testing-library helps find page elements by text, role, or label like a user would.

It makes tests easier to read and maintain.

Use it to write tests that focus on user experience, not page structure.