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?
Proper use of queries DOM Testing Library, which React Testing Library is built on top of, now exposes a screen object which has every query built-in. The changed best practice is to always use screen object and no longer destructure the object returned by render .
The screen object from the React Testing Library (RTL) provides methods for querying the rendered elements of the DOM in order to make assertions about their text content, attributes, and more. The screen.
Jest is a JavaScript test runner that lets you access the DOM via jsdom . While jsdom is only an approximation of how the browser works, it is often good enough for testing React components.
React Testing libraryEnzyme's shallow renderer doesn't render sub-components, so React Testing Library's render method is more similar to Enzyme's mount method. In React Testing Library, you don't need to assign the render result to a variable (i.e. wrapper ).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With