Erazihel
Erazihel

Reputation: 7605

Screen vs. render queries

There are two ways to use queries using React Testing Library.

You can either use the queries returned by the render method:

import React from 'react'
import { render } from '@testing-library/react'

...

const { getByText } = render(<div>Foo</div>)

expect(getByText('Foo')).toBeInTheDocument()

Or you can use the screen object:

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

...

render(<div>Foo</div>)

expect(screen.getByText('Foo')).toBeInTheDocument()

But there is no indication in the documentation about which one is the best option to use and why.

Can someone enlighten me?

Upvotes: 90

Views: 53197

Answers (2)

twiz
twiz

Reputation: 10568

screen is provided by @testing-library/dom, which is what @testing-library/react is built upon. When using the screen methods, they will query within the html <body> element, as described in the docs:

Because querying the entire document.body is very common, DOM Testing Library also exports a screen object which has every query that is pre-bound to document.body

render() is only in @testing-library/react. It returns an object similar to screen and the default is to also bind the queries to the <body>. By default, there is little difference, but you can customize its behavior by passing in options.

For example, you can specify an element other than the <body> to query within, and can even provide custom query methods.


Update:

Read the link in the answer from @rrebase

The maintainers of the project now recommend using screen, and they likely know much better than I do.

I am leaving my original recommendation for using render below if you would still like to read it.


To answer your question of which is the best, I would say using render() is better because the options make it more flexible, but to quote the docs:

You won't often need to specify options

Still, my preference would be to use the methods provided by render(), because if you ever decide to add in options, you wont need to remember to change all your queries.

Upvotes: 19

rrebase
rrebase

Reputation: 4219

The latest recommended option by the react-testing-library author Kent C. Dodds himself is to use screen.

The benefit of using screen is you no longer need to keep the render call destructure up-to-date as you add/remove the queries you need. You only need to type screen. and let your editor's magic autocomplete take care of the rest.

The only exception to this is if you're setting the container or baseElement which you probably should avoid doing (I honestly can't think of a legitimate use case for those options anymore and they only exist for historical reasons at this point).

Source: https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#not-using-screen

Upvotes: 105

Related Questions