Use Testing Library

Learn how to use the Testing Library to test your web application.

Testing library

The more your tests resemble the way your software is used, the more confidence they can give you.

Testing Library provides a way to write your tests so that they represent how the users actually use the web application. Let’s look at an example we currently have in the services/web/cypress/integration/spec.js file:

it("has the correct <h1>", () => {
  cy.contains("h1", "Great success!");
});

This test looks for a “heading 1” element and validates that its content is “Great success!”. From a developer’s perspective, this makes perfect sense. It tests the HTML structure and makes sure the correct text appears.

However, an end-user does not open a web application, inspect its source code, and look for an <h1> element to read its content. Their natural behaviour is to open a web application and look for text. The Testing Library provides helpers to write tests that match human natural behaviour more closely.

One aspect that is too often forgotten is how accessible a web application is! The Testing Library provides a getByRole function to find elements that are exposed in the accessibility tree. Please review the documentation for details on which Testing Library query to use.

Configuring the testing library

Let’s configure the Testing Library and look at an example of how to use it.

Click Run and change your working directory to services/web. Run the following command to install the dependency:

npm i -D @testing-library/cypress

Next, we need to tell Cypress about it in the services/web/cypress/support/commands.js file by adding the following list to make the new Testing Library commands available:

import "@testing-library/cypress/add-commands";

Use nano to open the above file.

Lastly, add a new test to the services/web/cypress/integration/spec.js file, right below the one called “has the correct <h1>”.

Note: There are two tests with the same description in different describe() blocks. Make sure you update the correct one:

// 'describe' is used to set the context of the test
describe("Sapper template app", () => {
  // https://testing-library.com/docs/guide-which-query
  ...
  // 'it' is used to specify the context and execution of the test
  it("has the correct heading", () => {
  // Finds elements with the given role name and matches the value to the element in the should function.
  cy.findByRole("heading").should("contain", "Great success!");
  });

  ...
});

Click Run again to save the changes.

Now, follow instructionsrunTest to run tests.

Get hands-on with 1400+ tech skills courses.