Understanding Testing Library Jest DOM

On This Page What is Jest DOM extension libraryFeatures of Jest DOM

March 31, 2026 · 7 min read · Testing Guide

Understanding Testing Library Jest DOM

In your journeying of testing web applications create using Javascript, you might decide to invest in testing frameworks, such as Jest, Cypress, etc. If you settle to go ahead with Jest as your testing framework, you can leverage the Jest DOM extension library to test the Document Object Model (DOM) in JavaScript applications, particularly web applications.

What is Jest DOM propagation library

Jest DOM is an extension designed for the Jest testing fabric. It enables Jest with specialized matchers for efficient testing and interaction with the Document Object Model (DOM) in JavaScript applications.

Jest DOM is an extension library for Jest that provides usage matcher to simplify examine DOM constituent. It enhances Jest & # 8217; s built-in assertions by offer more intuitive and readable queries, liketoBeInTheDocument (), toHaveTextContent (), and toHaveClass (),making it easier to screen web factor and their behavior in a browser environment.

Features of Jest DOM

Some of the characteristic of Jest DOM are:

  • Custom matchers: Jest DOM provides a range of custom matcher for enhanced assertions on the DOM elements, attributes, and substance.
  • Simulate events: With Jest DOM you can simulate user interaction and events such as keyboard events, etc in your trial.
  • Testing async: For asynchronous operations, such as where you are expect for factor to appear, etc, you can use the Jest DOM utilities.

Read More:

Use Jest DOM matchers

With the @ testing-library/jest-domlibrary, you can broaden Jest with the set of custom matchers it provides. These matchers help publish leisurely to read and preserve tests.

Let ’ s translate how to use custom-made matchers in your tests. We will use the.toExist ()matchmaker to verify if the Login push exists onhttps: //the-internet.herokuapp.com/login site.

Prerequisites of using Testing Library Jest DOM

Before you can start writing tests, you must set up your environment.

1. Setup directory and install Jest

  • In VScode, create a directory, namedJest.
  • Click Terminal & gt; New Terminal.
  • Run the following command to initialize a node project.
npm init
  • Run the following command to establish Jest.
npm install -- save-dev jest

2. Install Puppeteer

We will be using Puppeteer to compose our tests and Jest to run our tests. In the terminal, run the following command to install Puppeteer in our directory.

npm install puppeteer

3. Install the Jest DOM package

We will be using the custom matcher that the Jest DOM package run to assert the existence of theLogin button. In the terminus, run the following command to install the Jest DOM package.

npm install -- save-dev @ testing-library/jest-dom

Create and run the test employ Jest DOM

Here are the steps to create and run test using Jest DOM

Step 1. In VScode, open theJestdirectory.

Step 2. Create a custommatcher.test.jsfile in the directory.

Step 3. Add the following code to the file:

const puppeteer = require ('puppeteer '); describe ('Login Page Test ', () = & gt; {let browser; let page; beforeAll (async () = & gt; {browser = await puppeteer.launch (); page = await browser.newPage ();}); it ('should visit the login page and verify the login button ', async () = & gt; {await page.goto ('https: //the-internet.herokuapp.com/login '); // Custom matcher to check if an element be expect.extend ({toExist: (received) = & gt; {const passing = received! == null; if (pass) {return {message: () = & gt; ` Expected element not to exist, but it does. `, pass: true,};} else {return {message: () = & gt; ` Expected element to exist, but it does not. `, pass: false,};}},}); // Use Puppeteer to select the login button const loginButton = await page. $ (' # login & gt; button '); // Verify if the login button be expend the custom matcher expect (loginButton) .toExist (); // Take a screenshot for credit (optional) await page.screenshot ({path: 'login-page.png '});}, 10000); // Set a timeout of 10 mo (adjust as needed) afterAll (async () = & gt; {await browser.close ();});});

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Step 4.In your terminal, run the next command:

npm run test

The login-page.pngfile present thelogin page with the Login buttonexisting. In the code, theexpect (loginButton) .toExist ()argument uses the matcher to check the assertion for the Login push to exist.

How To Test a React App with Jest and React Testing Library

The Jest with React try library is often used for testing React apps because of the use it provides to do user-centric examination. The tests are besides readable and easygoing to conserve.

You can oftentimes use React Testing Library and Jest DOM together in your quiz workflow, as they serve different but complemental purposes. React Testing Library helps you with user-focused integration examination, while Jest DOM provides useful matchmaker for DOM element assertions within those tests.

To understand how to use the React testing library to try your React app, let ’ s view this scenario. We will be creating a unproblematic React app that include a Login button. We will create a test that checks whether the push exist using the.toBeInTheDocument ()function.

Read More:

Create a React App

Step 1In VScode, create a directory, namedcustom-matchers.

Step 2 Click Terminal & gt; New Terminal.

Step 3Create a React project and make a new React app:

npx create-react-app my-react-app

Step 4Change the directory tomy-react-app:

cd my-react-app

Step 5 Create a helloworld.jsfile and add the following code that creates the sample app:

// src/HelloWorld.js import React from 'react '; purpose HelloWorld () {// Function to deal the login push pawl const handleLogin = () = & gt; {alarm ('Login button clicked! '); // You can add your login logic here}; homecoming (& lt; div & gt; & lt; h1 & gt; Hello, World! & lt; /h1 & gt; & lt; p & gt; This is a simple React app. & lt; /p & gt; & lt; button onClick= {handleLogin} & gt; Login & lt; /button & gt; & lt; /div & gt;);} exportation default HelloWorld;

Step 6Add the following code in theApp.jsfile that adds thehelloworld.jsfile as a dependency:

… signification HelloWorld from './helloworld '; ….

Create the examination using Jest

Step 1In VSCode, from the sailing menu, expand thecustom-matchersdirectory.

Step 2 Create theApp.test.jsfile and add the following codification. TheApp.test.jsfile tests whether the Login button be using the.toBeInTheDocument () function:

import React from 'react '; import {render, screen} from ' @ testing-library/react '; importee HelloWorld from './helloworld '; trial ('it renders a login button ', async () = & gt; {render (& lt; HelloWorld / & gt;); // Use React Testing Library 's queryByText to find the login button const loginButton = screen.queryByText ('Login '); // Assert that the login button exists expect (loginButton) .toBeInTheDocument (); // const x= await page.screenshot ({path: 'login.png '});});

Note:Jest and React testing library is installed as part of the bid.

npx create-react-app

Read More:

Run your test

Step 1In VScode, clickTerminal & gt; New Terminal.

Step 2Run the following command to run the tryout.

npm test

The undermentioned screenshot show that the test passed and so did the assertions.

Advantages and Limitations of using Jest DOM

Advantages of Jest DOM

Let us understand some of the advantages that Jest DOM provides:

  • DOM testing:DOM interactions are do easier with the tradition matchmaker and utilities that Jest DOM provides.
  • Easygoing to read affirmation:As Jest DOM custom matchers are easy to say and sustain, they are preferred when writing tests that involve DOM interactions.
  • Async testing:With asynchronous scenarios such as waiting for a DOM element, etc, Jest utilities are very utilitarian.

Limitations of Jest DOM

Though Jest DOM has plenty of advantages, when making a determination, do consider the following disadvantages:

  • Needs Jest:If your tests are already written in some other testing framework, Jest DOM adoption might demonstrate difficult.
  • Requires initial learning:If your developers are new to using testing library, adjust live systems to use Jest DOM might slow down acceptance.
  • Overuse:Because of the easiness that the library provides, you might overuse the matchers leading to very tightly-coupled tests.

Good Practices for using Jest DOM

Here are some best practices for using Jest DOM:

  1. Use Semantic Queries: Prefer queries likegetByRole, getByLabelText,or getByText over getByTestIdto ensure tests are more maintainable and accessible.
  2. Write Readable Tests: Focus on clarity by continue assertions simple and descriptive, ensuring tests are easygoing to understand.
  3. Use beforeEach and afterEach: Set up and pick up your test environment to prevent tests from interfering with each other.
  4. Mock External APIs: Use Jest ’ s mock functions to simulate API calls, ensuring that trial focus on the component rather than international addiction.
  5. Test Accessibility: Always test for accessibility by checking if element are properly interactive and accessible for screen readers and keyboard.
  6. Avoid Over-Mocking: Mock solely what ’ s necessary to foreclose overly complex and brickly examination.
  7. Use blind for Queries: screenmakes querying elements more pliant and approachable within the test suit

Conclusion

In this article, we hear how to use the Jest DOM library and the custom matchmaker that it provides. We also larn how to use them with the React App and leverage the UI essay ease it offers. Though Jest is racy and offers ease of creating tests, it perform limit the orbit of browsers and devices that you can test in real-time situation.

For stable testing, you must and for that using a, such as, is a great choice. Access to multiple device helps you prognosticate and deal matter before your product attain production.

Tags
13,000+ Views

# Ask-and-Contributeabout this matter with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free