Search code examples
javascriptreactjsreact-testing-library

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?


Solution

  • 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