Test on Real Devices

Give your users a seamless experience by testing on 3500+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide What is Cypress Testing Library and its Usage

What is Cypress Testing Library and its Usage

By Gurudatt S A, Community Contributor -

Cypress is a powerful testing framework for automating web application tests, and its integration with the Cypress Testing Library enhances its functionality. By combining Cypress with the DOM Testing Library, developers can write cleaner, more readable tests that interact with web elements to mirror how users engage with them.

This article explores the Cypress Testing Library, its APIs, and how it simplifies querying elements in tests, improving the overall testing experience.

What is Cypress Testing Library?

Cypress Testing Library is an extension of the popular DOM Testing Library designed to work seamlessly with the Cypress testing framework. It allows developers to write tests in a way that mirrors how users interact with web pages, making the tests more readable, maintainable, and effective. By integrating the Testing Library’s querying methods (like findByRole, findByLabelText, and findByText) into Cypress tests, this library enhances the ability to select elements on a page using user-centric queries rather than relying on low-level CSS selectors or XPath.

The Cypress Testing Library encourages testing practices focusing on how users interact with elements, such as by role, label, or text content. This approach ensures tests are less dependent on implementation details, making them more maintainable and resilient to changes in the code.

Key Features of Cypress Testing Library

The Cypress Testing Library offers several key features designed to improve the testing process for web applications:

  • Familiar Query Methods: It integrates Testing Library’s popular query methods, such as findByRole, findByText, findByLabelText, and findByTestId, making it easier for developers familiar with the library to adapt to Cypress.
  • User-Centric Queries: The focus is on selecting elements the way users would interact with them, rather than relying on implementation details like CSS classes or IDs, leading to more reliable tests.
  • Built-in Accessibility Features: By using queries like findByRole, the library promotes writing tests that are accessible, ensuring that elements are found based on their role, which enhances test readability and accessibility.
  • Minimal Setup: Once installed, the Cypress Testing Library requires minimal setup. Importing it into your Cypress commands file adds all necessary commands to interact with elements.
  • Chainable API: The library’s API works seamlessly with Cypress’s chainable commands, allowing tests to be written cleanly and concisely without excessive chaining.
  • Cross-Platform Compatibility: It works across various browsers and devices, allowing for consistent and comprehensive testing in Cypress, even when integrated with services like BrowserStack for real-device testing.

Benefits of Using Cypress Testing Library

Below are some key benefits of using Cypress Testing Library:

  • Improved Test Maintainability: User-centric queries make tests less prone to breaking from small implementation changes.
  • Better Readability: Intuitive and clean API enhances test clarity, focusing on user behavior.
  • Enhanced Accessibility: Encourages testing for accessibility by using queries like findByRole.
  • Simplified Code: Reduces the need for custom commands and minimizes code duplication.
  • Faster Test Execution: Optimized for speed, leveraging Cypress’s fast execution.
  • Consistency: Aligns with other Testing Library practices, making it easy for teams familiar with those libraries.

Installation and Setup of Cypress Testing Library

To install the cypress-testing-library, in the terminal from your root cypress project, execute the below command:

npm install --save-dev @testing-library/cypress

This will install the cypress-testing-library as a dev dependency. 

Once the installation is successful, you need to import the reference of cypress-testing-library in our cypress/support/commands.js file.

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

This will chain all of the cypress-testing-library API to cy object.

DOM Testing Library vs Cypress Testing Library

While both libraries simplify DOM testing, there are key differences between the DOM Testing Library and the Cypress Testing Library.

  • Element Handling: The Cypress Testing Library supports both jQuery elements and DOM nodes, aligning with Cypress’s internal use of jQuery. In contrast, the DOM Testing Library exclusively works with DOM nodes. When chaining queries, the Cypress Testing Library retrieves the first DOM node from a collection and uses it for subsequent functions.
  • Querying: The Cypress Testing Library does not support query* queries. Instead, it utilizes assertions like should(‘not.exist‘) to check for the absence of an element. Additionally, get* queries are unavailable, and find* queries do not use the Promise API from the DOM Testing Library. Instead, they rely on Cypress’s built-in retryability and error messaging for query failures.
  • Selecting Multiple Elements: The findAll* queries in Cypress Testing Library can select multiple elements, similar to Cypress’s built-in commands. This differs from DOM Testing Library, where find* queries will fail if multiple matching elements are found. Cypress commands, however, handle multiple elements without issue. For example, using cy.findAllByText(‘Some Text’).click() will automatically fail if more than one element is returned, whereas Cypress testing handles actions on multiple elements seamlessly.
  • Enforcing Single Elements: If only one element is expected, Cypress allows for automatic failure when multiple elements are returned, like in the case of cy.findAllByText(‘Some Text’).should(‘have.length’, 1). This will fail if more than one match is found, unlike some other testing libraries which may need explicit handling for multiple elements.

Cypress Testing Library APIs

There are several APIs in the Cypress Testing Library, as seen below.

APIDefinition
findByPlaceholderText<input type=“text” placeholder=“Input 1” id=“by-text-input”>

With an element like above, we can then use the API as like below

cy.findByPlaceholderText(“Input 1”)

With this API we can find the element by its Placeholder text.

This api will throw error if there are more than 1 matching element

findAllByPlaceholderText<input type=“text” placeholder=“Input 1” id=“by-text-input”>
<input type=“text” placeholder=“Input 2” id=“by-text-input-2”>With the above elements, if we need to find both the elements then we write cypress command likecy.findAllByLabelText(/^Input \d$/)
findByLabelText<label for=“by-text-input”>Label 1</label>

With above element we can see that Label element has text “Label 1”

Our Cypress command will be 

cy.findByLabelText(“Label 1”)

findAllByLabelText<label for=“by-text-input”>Label 1</label>
<label for=“by-text-input-2”>Label 2</label>If we want get multiple elements matching for the provided label text, we can write our cypress command likecy.findAllByLabelText(/^Label \d$/)
findByText<button onclick=“this.innerText = ‘Button Clicked'”>Button Text 1</button>

With the above element, if we need to find the element by its matching text, we can write our cypress command like

cy.findByText(“Button Text 1”)

findAllByText<button onclick=“this.innerText = ‘Button Clicked'”>Button Text 1</button>
<button onclick=“this.innerText = ‘Button Clicked'”>Button Text 2</button>We can use this API when we want to find more than 1 element by its textcy.findAllByText(/^Button Text \d$/)
findByDisplayValue<input type=“text” value=“Display Value 1”>

We can use this API when we want to find the element by its value attribute

cy.findByDisplayValue(“Display Value 1”)

findAllByDisplayValue<input type=“text” value=“Display Value 1”>
<input type=“text” value=“Display Value 2”>We can use this API when we want to find multiple elements matching the valuecy.findAllByDisplayValue(/^Button Text \d$/)
findByAltText<img src=“data:image/png;base64,” alt=“Image Alt Text 1” onclick=“this.style.border = ‘5px solid red'”>

We can use this API when we want to find the element based on its alt attribute

cy.findByAltText(“Image Alt Text 1”)

findAllByAltText<img src=“data:image/png;base64,” alt=“Image Alt Text 1” onclick=“this.style.border = ‘5px solid red'”>
<img src=“data:image/png;base64,” alt=“Image Alt Text 2” onclick=“this.style.border = ‘5px solid red'”>We can use this API when we want to find multiple elements matching the alt attribute
findByTitle<span title=“Title 1”>1</span>

We can use this API when we want to find element based on its title attribute

cy.findByTitle(“Title 1”)

findAllByTitle<span title=“Title 1”>1</span>
<span title=“Title 2”>2</span>We can use this API when we want to find multiple elements based on its title attributecy.findAllByTitle(/^Title \d$/)
findByRole<div role=“dialog”>dialog 1</div>

We can use this API when we want to find element based on its role attribute

cy.findByRole(“dialog”)

findAllByRole<div role=“dialog”>dialog 1</div>
<div role=“dialog-fake”>dialog 2</div>We can use this API when we want to find multiple elements based on role attributecy.findAllByRole(/^dialog/)
findByTestId<img data-testid=“image-with-random-alt-tag-1” src=“data:image/png;base64,” onclick=“this.style.border = ‘5px solid red'” alt=“Image Random Alt Text 0.9710155761447143”>

We can use this API when all our elements are added with custom test attribute like data-testid.

Then we can just pass the custom attribute value to this API.

cy.findByTestId(“image-with-random-alt-tag-1”)

Note: We can also change the default custom attribute by adding below line in our cypress/support/index.js

import {configure} from ‘@testing-library/cypress’

configure({testIdAttribute: ‘data-test-id’})

findAllByTestId<img data-testid=“image-with-random-alt-tag-1” src=“data:image/png;base64,” onclick=“this.style.border = ‘5px solid red'” alt=“Image Random Alt Text 0.9710155761447143”>

<img data-testid=“image-with-random-alt-tag-2” src=“data:image/png;base64,” onclick=“this.style.border = ‘5px solid red'”>We can use this API to find multiple elements based on the custom test attributecy.findAllByTestId(/^image-with-random-alt-tag-\d$/) 

 

Cypress test examples using these commands can be found here

Below is the example cypress test using BrowserStack demo app

it("validate the element existance", () => {
cy.visit("https://www.bstackdemo.com/");
cy.findByDisplayValue("Apple").should("exist");
});

BrowserStack Automate Banner

Best Practices for Using Cypress Testing Library

Below are some key best practices for using Cypress Testing Library:

  • Prioritize Accessibility: Focus on testing elements like users would interact with them. This ensures that tests are both user-centric and accessible.
  • Keep Tests Simple and Readable: Write straightforward tests that target a single aspect of functionality. This makes tests easier to maintain and understand.
  • Avoid Over-reliance on Implementation Details: Design tests that depend on user-facing properties, like labels or text, rather than internal implementation details. This reduces the fragility of tests to changes in the codebase.
  • Leverage Cypress’s Features: Use Cypress’s built-in features, such as automatic retries, to handle occasional UI delays or transitions without complicating test logic.
  • Focus on Realistic User Flows: Ensure your tests reflect real user interactions and workflows, making the testing process more meaningful and relevant to actual usage.

Talk to an Expert

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Conclusion

This article discussed how to leverage the cypress-testing-library to hide multiple chaining of the commands. This will keep the code clean as well as avoid users creating their own methods in the framework which might just increase the code duplication and redundant functions.

The cypress-testing-library APIs are self explanatory on what it does, hence it gives clarity from a readability perspective. And these APIs are similar to DOM Testing Library, developers will also have benefit of using the cypress-testing-library API similar to DOM testing library.

Whenever running Cypress tests, it is recommended to test on real devices so that the real user conditions can be taken into account for better accuracy of test results. Tools like BrowserStack Automate help QAs by providing access to 3500+ device browser combinations for a comprehensive automated testing.

Run Cypress Tests on Real Devices

Tags
Automated UI Testing Automation Frameworks Cypress Website Testing

Featured Articles

What is Cypress Page Object Model?

What’s new in Cypress 10? How it will change your current testing requirements

Automation Tests on Real Devices & Browsers

Seamlessly Run Automation Tests on 3500+ real Devices & Browsers