Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
Erazihel Avatar asked Apr 28 '20 14:04

Erazihel


People also ask

Should I use screen in React testing library?

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 .

What is screen in React testing library?

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.

Which testing library is best for React?

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.

Does React testing library shallow render?

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 ).


1 Answers

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

like image 57
rrebase Avatar answered Sep 19 '22 20:09

rrebase