Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am building out tests in my React app that was built with create-react-app and I'm trying to understand what the difference is between screen.getByText() and simply getByText(). For instance, the documentation shows this kind of example:

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

it('renders a title of "Dashboard"', () => {
  render(<App />);
  expect(screen.getByText('Dashboard')).toBeInTheDocument();
});

But I see that I can do this:

it('renders a title of "Dashboard"', () => {
  const { getByText } = render(<App />);
  expect(getByText('Dashboard')).toBeInTheDocument();
});

I haven't found what the difference is between using screen.getByText() vs. simply using getByText() like I've shown above.

What are the differences, and are there advantages in using one over the other in various scenarios?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
211 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's a convenience thing. Using screen you'll find that you no longer need to constantly/explicitly have to destructure the return value of the render method to get to the selector functions (that's basically it).

The PR that introduced the feature has a clear explanation of the rationale behind it:

https://github.com/testing-library/dom-testing-library/pull/412

The only caveat is in the scenario where you provide an explicit container argument to the render method - as the screen based selector would match all elements on the document.body (where as if you destructure the render result, the selector functions will be scoped to elements within the container you provided).

If you're starting out with that library I also suggest that you take a peek into this Kent Dodds article (the same who introduced the feature and a person which is a big reference in this area), which has a bunch of goodies/best practices using testing-library with the rationale behind each recommendation:

https://kentcdodds.com/blog/common-mistakes-with-react-testing-library


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...