'react-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 1:[1]

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.

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.

Solution 2:[2]

Simply add to the first line of your test file, to allow access to the virtual DOM elements,

/**
 *  @jest-environment jsdom
 */

Reference:

  1. Related bug
  2. Documentation
  3. Common mistakes

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 twiz
Solution 2