Using the debug method
The debug
method, accessible from the screen
object, is a helpful tool in React Testing Library's API that allows you to see the current HTML output of components as you build out your tests. In this section, we will learn how to display the resulting DOM output of an entire component or specific elements.
Debugging the entire component DOM
You can use the debug
method to log the entire DOM output of a component when you run your test:
it('displays the header and paragraph text', () => { render(<Travel />) screen.debug() })
In the preceding code, we first rendered the Travel
component into the DOM. Next, we invoked the debug
method. When we run our test, the following will be logged to the console:
In the previous screenshot, the entire DOM output of the Travel
component is logged to the screen. Logging the whole output can help you build out your test, especially when interacting with one element in the DOM affects elements elsewhere in the current DOM. Now you know how to log the output of the entire component DOM to the screen. Next, we will learn how to log specific elements of the DOM to the screen.
Debugging specific component elements
You can use the debug
method to log specific elements of the resulting component DOM to the screen:
it('displays the header and paragraph text', () => { render(<Travel />) const header = screen.getByRole('heading', { name: /travel anywhere/i }) screen.debug(header) })
In the previous code, first, we rendered the Travel
component into the DOM. Next, we used the getByRole
method to query the DOM for a heading with the name travel anywhere
and saved it to a variable named header
. Next, we invoked the debug
method and passed in the header
variable to the method. When we run our test, the following will be logged to the console:
When you pass in a specific DOM node found by using one of the available query methods, the debug
method only logs the HTML for the particular node. Logging the output for single elements can help you only focus on specific parts of the component. Be sure to remove any debug
method code from your tests before making commits because you only need it while building out the test.
Now you know how to use the debug
method to render the resulting DOM output of your components. The debug
method is a great visual tool to have while writing new tests and also when troubleshooting failing tests.