Course contentsShow
← React
Lesson 2048 of 2,39646. Testing React with RTLFree lesson

The debug() Function for Inspection

Using screen.debug() to print the current DOM tree, essential for understanding test failures.

The debug() Function for Inspection

What you'll learn: How to use screen.debug() to see what RTL actually rendered when your test fails.

Why You Need debug()

When a test fails, you're often left wondering: "What does the DOM actually look like right now?" RTL's screen.debug() is your X-ray vision—it prints the current DOM tree to the console, showing you exactly what the test sees.

Think of it like opening DevTools during a test. You can't click around and inspect elements, but debug() gives you a snapshot of the rendered output at that exact moment.

Using screen.debug()

After calling render(), you have access to screen.debug():

import { render, screen } from '@testing-library/react';

function Greeting({ name }: { name: string }) {
  return <h1>Hello, {name}!</h1>;
}

test('renders greeting', () => {
  render(<Greeting name="Alice" />);
  
  screen.debug(); // Prints entire DOM tree to console
});

This outputs the full HTML structure RTL rendered, making it easy to verify class names, text content, or why a query is failing.

Debugging Specific Elements

You can also debug just one element instead of the entire tree:

const heading = screen.getByRole('heading');
screen.debug(heading); // Only prints <h1>Hello, Alice!</h1>

This is useful when debugging deeply nested components—you focus on the relevant part without drowning in unrelated markup.

When to Use It

Use screen.debug() liberally while writing tests. When a query fails or returns unexpected results, add it before the failing line to see what's actually there versus what you expected.

Key Takeaway: screen.debug() is your essential debugging tool in RTL—use it to inspect the rendered DOM whenever tests behave unexpectedly, giving you the visibility needed to understand what went wrong.