How to use the react testing library debug method?

On This Page What is React Testing Library?Core

January 05, 2026 · 15 min read · Testing Guide

How to use the react testing library debug method?

When publish tests with React Testing Library, it ’ s indispensable to interpret the rendered output of the components. The debug () method is an effective characteristic that helps to inspect the current DOM tree in your test environment.

Overview

What is React Testing Library?
React Testing Library is a lightweight tool for testing React component based on user interactions. It concentrate on behavior rather than implementation, making tests more reliable and easy to maintain.

Core Methods in React Testing Library:

  • render(): Renders a component to the virtual DOM for testing and returns usefulness functions.
  • screen: Provides access to query methods without postulate to destructure fromrender().
  • container:Gives unmediated access to the DOM for edge cases where standard queries aren & # 8217; t plenty.

Best Practices for React Testing Library Debugging:

  • Use screen.debug () to visit the practical DOM and spot missing elements.
  • Verify accessibility attributes like role and label for best queries.
  • Clean up debug logarithm after resolving issues to maintain test tidy.
  • Base exam on user-visible DOM, not component internals.

Read this usher to understand the React Testing Library through the debugging process, examples, and best praxis to follow.

What is React Testing Library?

React Testing Libraryis a lightweight testing library built to test React components from the user ’ s view.

Instead of focusing on the interior implementation or component construction, the React Testing Library helps examine how user interact with your application, such as clicking buttons, recruit text, and say seeable message.

This facilitate create more robust and maintainable tests less prone to breakage from UI refactors or internal changes.

Must Read:

Core Methods in React Testing Library

Here are the core methods that want to be follow for write effective and user-focused component tests:

1. render ()

The render () method is used to render a React ingredient into a virtual for testing. It returns a set of use that help you create queries and interact with the rendered output.

Syntax:

import {supply} from ' @ testing-library/react '; render (& lt; MyComponent / & gt;);

Example:

const {getByText} = render (& lt; Greeting name= '' Ayush '' / & gt;); anticipate (getByText ('Hello, Ayush ')) .toBeInTheDocument ();

2. screen ()

The screen object is a globally accessible feature that provides access to all query functions. It annihilate the need to destructure queries from the render result and promotes more ordered test patterns.

Syntax:

import {render, screen} from ' @ testing-library/react '; render (& lt; MyComponent / & gt;); expect (screen.getByText ('Welcome ')) .toBeInTheDocument ();

3. container ()

This is useful for inspecting the full DOM tree or using DOM APIs directly, though it ’ s recommended only when enquiry like getByRole or getByText aren & # 8217; t sufficient.

Syntax:

const {container} = render (& lt; MyComponent / & gt;); expect (container.firstChild) .toHaveClass ('my-component ');

Also Read:

How to add React Testing Library to React apps

Here are the steps to be postdate for adding React Testing Library to React apps:

Step 1: Install Required Packages

To begin, instal React Testing Library along with its dependence:

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

For the Yarn users:

thread add -- dev @ testing-library/react @ testing-library/jest-dom

Step 2: Set Up Jest DOM in Your Test Environment

  1. If using Create React App, open src/setupTests.js (this file is auto-detected).
  2. Add the following line:
import ' @ testing-library/jest-dom ';

Step 3: Create Your Initiatory Test File

Create a trial file in a separate _tests_ folder.

importation {render, screen} from ' @ testing-library/react '; import App from './App '; test ('renders welcome message ', () = & gt; {render (& lt; App / & gt;); expect (screen.getByText (/welcome to react/i)) .toBeInTheDocument ();});

Step 4: Run Your Tests

Use the built-in exam bidding to run your test suite:

npm test

or

yarn test

Step 5: Add Testing Scripts to package.json (Optional)

For easier test execution, delineate a custom script:

`` scripts '': {'' test '': `` react-scripts test '', '' test: watch '': `` react-scripts test -- watchAll '', '' tryout: coverage '': `` react-scripts tryout -- coverage ''}

How to use React Testing Library

Follow these stairs to use React Testing Library to prove a unproblematic React part:

Step 1: A component called Greeting.js is created that displays a message based on user input.

import React, {useState} from 'react '; function Greeting () {const [name, setName] = useState (``); homecoming (& lt; div & gt; & lt; h1 & gt; Hello {name? name: 'Guest '} & lt; /h1 & gt; & lt; input type= '' text '' placeholder= '' Enter your name '' onChange= {(e) = & gt; setName (e.target.value)} / & gt; & lt; /div & gt;);} export default Greeting;

Step 2: Write a Test Using React Testing Library

import {render, screen, fireEvent} from ' @ testing-library/react '; import Greeting from './Greeting '; test ('renders default greeting and update when exploiter eccentric ', () = & gt; {render (& lt; Greeting / & gt;); anticipate (screen.getByText (/Hello Guest/i)) .toBeInTheDocument (); fireEvent.change (screen.getByPlaceholderText (/enter your name/i), {target: {value: 'Ayush '},}); expect (screen.getByText (/Hello Ayush/i)) .toBeInTheDocument ();});

Step 3: In the end, run:

npm test

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

Must Read:

What is React Testing Library Debug Method?

Think of thereact testing library debugfunction in React Testing Library like a magnifying glass. When you & # 8217; re testing your React component and you want to see exactly what & # 8217; s being create or what it looks like, you use thisreact test library debuggingexaggerate glass.

For instance, say you have a component that you & # 8217; re examination:

const {debug} = render (& lt; MyComponent / & gt;);

Here, render (& lt; MyComponent / & gt;)is like pull or creating your constituent on a part of paper. Now, you want to see this drawing, right? That & # 8217; s when you use your debug magnifying glass:

debug();

When you do this, it & # 8217; s like the magnifying glass is evidence you exactly what your draftsmanship (or component) looks like in the terminal where you & # 8217; re scat your test.

And the cool thing? You can usedebug to look at specific constituent of your drawing too. For illustration, if you feature a bit of text like & # 8216; Hello & # 8217; in your component and you just want to seem at that, you can do:

Here, getByText (& # 8216; Hello & # 8217;)finds the & # 8216; Hello & # 8217;text in your component (like designate to it on your drawing), and thendebug (helloText)lets you use the magnifying glass to seem specifically at this& # 8216; Hello & # 8217;text component of your component.

So, debug is a handy puppet to visualize what & # 8217; s going on when you & # 8217; re testing your part. It & # 8217; s like a supporter showing you your test & # 8216; drawings & # 8217;.

const {getByText, debug} = render (& lt; MyComponent / & gt;); const helloText = getByText ('Hello '); debug (helloText);

Read More:

How to debug in react testing library use screen.debug () method?

screen.debug () print the current state of the rendered DOM, which helps to visually inspect what your component is rendering and why a query might be fail.

1. Automatic Logging

This method logs the current DOM tree to the console. This can be inserted anywhere in the test code to visualize the component ’ s rendered HTML.

Syntax:

screen.debug ();

Example:

import {render, screen} from ' @ testing-library/react '; importation Greeting from './Greeting '; trial ('debug example ', () = & gt; {render (& lt; Greeting / & gt;); screen.debug ();});

Output:

& lt; body & gt; & lt; div & gt; & lt; h1 & gt; Hello Guest & lt; /h1 & gt; & lt; input placeholder= '' Enter your name '' type= '' text '' / & gt; & lt; /div & gt; & lt; /body & gt;

Also Read:

2. Understanding screen.debug () Syntax

React Testing Library ’ s screen object provides the debug () method and comes with a few helpful parameters:

  • element:A specific DOM ingredient or subtree to mark.
  • maxLength:Limit the output length for readability.

3. Example Using screen.debug ()

Check out this practical model using screen.debug () to identify an issue in the test:

Component:

office Greeting () {return (& lt; div & gt; & lt; h1 & gt; Hello Guest & lt; /h1 & gt; & lt; button shroud & gt; Hidden Button & lt; /button & gt; & lt; /div & gt;);}

Test Case:

importation {render, screen} from ' @ testing-library/react '; significance Greeting from './Greeting '; examination ('debugging a concealed ingredient ', () = & gt; {render (& lt; Greeting / & gt;); const button = screen.queryByRole ('button '); screen.debug (); expect (button) .not.toBeVisible (); // This will fail unless you use queryByRole correctly});

Output:

& lt; body & gt; & lt; div & gt; & lt; h1 & gt; Hello Guest & lt; /h1 & gt; & lt; button hidden= '' '' & gt; Hidden Button & lt; /button & gt; & lt; /div & gt; & lt; /body & gt;

How to test a method in React Testing Library

Suppose you have a component callCounterthat display a count and has a method calledincrementCountto increase the count when a push is clicked. Here & # 8217; s how you can test it using React Testing Library:

Counter Component (Counter.js)

meaning React, {useState} from 'react '; function Counter () {const [count, setCount] = useState (0); const incrementCount = () = & gt; {setCount (count + 1);}; return (& lt; div & gt; & lt; p & gt; Count: {count} & lt; /p & gt; & lt; button onClick= {incrementCount} & gt; Increment & lt; /button & gt; & lt; /div & gt;);} export default Counter;

Counter Test (Counter.test.js)

meaning {render, fireEvent} from ' @ testing-library/react '; import Counter from './Counter '; test ('counter increments the count ', () = & gt; {const {getByText} = render (& lt; Counter / & gt;); const push = getByText ('Increment '); fireEvent.click (button); const countElement = getByText ('Count: 1 '); expect (countElement) .toBeInTheDocument ();});

In this test, you & # 8217; re provide theCountercomponent and finding the & # 8220;Increment& # 8221; button usinggetByText. Then, you assume a exploiter clicking the button usingfireEvent.click. Finally, you find the component that display the updated count and assert that it & # 8217; s displaying the expected enumeration.

By quiz the element behavior through user interactions, you indirectly try theincrementCountmethod. You & # 8217; re control that when the push is clicked, the count update as expect. This approach focuses on essay the component from the user & # 8217; s perspective rather than directly testing the method implementation.

This way, your tests are more robust and flexible, allowing you to do change to the implementation details of the component without breaking the tests.

With BrowserStack, you can easily test your React apps across multiple browsers, devices, and run systems, ensuring seamless compatibility and optimal user experience. One of the key products offered by. It allows you to test your React mobile applications in real-time on real device, control precise rendering and functionality across various blind sizes and platforms. You can accession App Live.

Waiting for Appearance and Disappearance

To wait for element appearance or disappearance in React Testing Library, you can utilize various mechanisms supply by the library. These mechanism countenance you to wait for specific constituent to appear or vanish before performing assertions in your trial. Here are a few approaches you can use:

1. findBy: Use findByquery to await for an element to appear. It returns a promise that resolves when the element is found or rejects if not found within the specified timeout.

const ingredient = await screen.findByText ('Hello ');

2. waitFor: Utilize waitForto wait until a condition is met. It repeatedly checks the condition until it resolves or reaches the specified timeout.

await waitFor (() = & gt; {const element = screen.queryByText ('Hello '); expect (ingredient) .toBeNull ();});

3. queryBy: Use queryByqueries to check for the absence of an element. It returns null if the component is not found, allowing conditional averment ground on its front or absence.

const factor = screen.queryByText ('Hello '); expect (ingredient) .toBeNull ();

These method help you expect for element appearance or disappearance in React Testing Library tryout, ensuring reliable and accurate testing of your components.

Testing for Appearance and Disappearance

Consider a scenario where you have a ingredient calledNotificationthat displays a notification substance. Initially, the presentment is not visible, but it seem when a button is click. After a few seconds, it mechanically disappears.

import React, {useState, useEffect} from 'react '; function Notification () {const [isVisible, setIsVisible] = useState (false); useEffect (() = & gt; {let timeout; if (isVisible) {timeout = setTimeout (() = & gt; {setIsVisible (false);}, 3000);} homecoming () = & gt; {clearTimeout (timeout);};}, [isVisible]); return (& lt; div & gt; & lt; button onClick= {() = & gt; setIsVisible (true)} & gt; Show Notification & lt; /button & gt; {isVisible & amp; & amp; & lt; p & gt; Notification message & lt; /p & gt;} & lt; /div & gt;);} exportation nonremittal Notification;

Notification Test (Notification.test.js)

import {render, screen, fireEvent, waitForElementToBeRemoved} from ' @ testing-library/react '; import Notification from './Notification '; test ('notification appears and disappears ', async () = & gt; {render (& lt; Notification / & gt;); const push = screen.getByText ('Show Notification '); fireEvent.click (button); const notification = screen.getByText ('Notification content '); await (notification) .toBeInTheDocument (); await waitForElementToBeRemoved (() = & gt; screen.getByText ('Notification content ')); await (notification) .not.toBeInTheDocument ();});

In this instance, we & # 8217; re testing the appearance and disappearance of the notification. First, we render theNotificationcomponent and click the & # 8216;Show Notification& # 8216; button. We then swear that the notification message appears in the DOM. We usewaitForElementToBeRemovedto wait for the apprisal message to disappear from the DOM, and so we assert that it is no longer in the document.

By using these proficiency, you can efficaciously test the appearance and fade of elements in your React components, providing confidence in the behavior and functionality of your covering.

Pro-Tip:BrowserStack also provides parallel testing capabilities, allowing you to run multiple tests concurrently, significantly trim your testing clip. This helps you achieve fast time to market for your React coating. Learn more about.

How to Debug specific constituent elements

You can debug specific ingredient elements expend React Testing Library as seen in the code below:

import {render, screen} from ' @ testing-library/react '; import YourComponent from './YourComponent '; exam ('debug specific ingredient constituent ', () = & gt; {render (& lt; YourComponent / & gt;); const specificElement = screen.getByText ('Specific Element '); screen.debug (specificElement);});
  • In this representative, when you run this exam, you will render theYourComponentthat you need to test.
  • Next, you will usegetByTextto select the specific element you need to debug free-base on its text message.
  • Finally, by usingdebug, you will print the debug info of the specific constituent. The debug yield will cater you with valuable perceptivity into the state and properties of that element.
  • By running this test, you will see the debug yield in the examination console, which helps you understand and debug the choose component element during testing.

Using logRoles () for Debugging

import {render, screen, logRoles} from ' @ testing-library/react '; import YourComponent from './YourComponent '; test ('create test log utilise logRoles ', () = & gt; {render (& lt; YourComponent / & gt;); logRoles (screen.getByRole);});
  • In this example, you import the necessary functions from React Testing Library. Then, you render theYourComponentthat you want to test.
  • After rendering the component, you use thelogRolesfunction, passscreen.getByRoleas a parameter. This function generates screen logarithm for the roles exhibit in the component.
  • When you run this exam, thelogRolesmapping will generate test log in the testing console, providing you with information about the roles and their accessibility within the constituent.
  • These logs can be useful for translate the roles utilize in your component, ensuring proper accessibility, and assisting in documenting and validating the features of your covering.

Debugging with logTestingPlaygroundURL () Method

logTestingPlaygroundURL () is a utility part from React Testing Library that lumber a unique link to Testing Playground.

When the link is opened in a browser, it loads the current rendered DOM and highlights the best way to query your elements using getByRole, getByLabelText, etc.

Example:

significance {render, blind, logTestingPlaygroundURL} from ' @ testing-library/react '; import Greeting from './Greeting '; test ('debug with testing playground ', () = & gt; {render (& lt; Greeting / & gt;); logTestingPlaygroundURL ();});

Output:

Open this URL in your browser: https: //testing-playground.com/ # markup= ...

Better Practices for React Library Debugging

Here are some of the best practices to be followed for React Library Debugging:

  • Use screen.debug () to Inspect the DOM:This method allows you to view the current virtual DOM output at any point in your trial. It helps identify missing element that may cause assertion failures.
  • Check for Accessibility Attributes:Use debugging to verify that elements feature appropriate purpose, labels, and accessible name for effective queries.
  • Keep Debug Output Temporary:Remove or comment out screen.debug () and other debug helpers once tests pass to keep exam output clean and focused.
  • Update Tests Based on DOM, Not Implementation:Use debug tools for queries that mull user behaviour, not internal structure.

Testing on Real Device Cloud with BrowserStack

Instead of managing an in-house gimmick lab, teams can instantly test their apps on real devices hosted in the cloud to insure accuracy and speed.

aid in by giving instant access to existent mobile and desktop devices. It can also run manual tests or integrate with automation tools like,, or, helping in bug-free, responsive, and user-ready application testing.

Key Features of BrowserStack Live:

  • Real Device Testing:Instantly test on 3,500+ existent device and browsers, including the latest iPhones, Androids, Windows, and macOS machines.
  • Live Interactive Testing:Perform, live, and interactive examination sessions in existent time to study real user experiences on various devices and browser.
  • No Setup or Maintenance Required:Test now on without the hassle of setting up or maintaining your gimmick lab.
  • Secure and Private:BrowserStack Live offers strong security to protect your test data with encrypted connections and individual session choice.

Talk to an Expert

Conclusion

In conclusion, the React Testing Library (RTL) is a potent tool for testing React applications. By focusing on user-centric examination and encouraging tests that resemble existent user interaction, RTL helps secure that your application functions as specify from the user & # 8217; s perspective. Companies like Facebook and Airbnb have leveraged RTL to enhance the reliability and user experience of their projection.

By leverage BrowserStack & # 8217; s robust program, React Developers can profit self-confidence in the caliber and performance of their applications, leading to heighten user satisfaction and increased productiveness. Experience the benefits of BrowserStack & # 8217; s comprehensive testing program for React applications.

Utilitarian Resources for React

Tags
77,000+ Views

# Ask-and-Contributeabout this topic 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