Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between getByText and screen.getByText in RTL

I'm new to React-Testing-Library and found a couple of examples on the web of people using view.getByText('Greeting') and screen.getByText('Greeting'), like in the following code.

Is there any difference between them?

    import React from 'react'
    import { render, screen } from '@testing-library/react'
    import '@testing-library/jest-dom/extend-expect'
    import { App } from "./App";
    
    test("render the correct context", ()=>{
      const view = render(<App />);
      view.getByText("Greeting");
      screen.getByText("Greeting");
    });

Can anyone please tell me in detail?

like image 789
Bablu Ahmed Avatar asked Nov 11 '20 19:11

Bablu Ahmed


2 Answers

TLDR; They are very often the same thing.

The difference

getByText will query inside baseElement

screen.getByText will query inside document.body

We usually don't specify a custom container or baseElement inside the render function, this causes it to default to document.body.

Therefore getByText and screen.getByText--or any of the other queries--are usually interchangeable.

import { render, screen } from '@testing-library/react'

test("render the correct context", ()=>{
  const { getByText } = render(<App />, { baseElement });
  getByText("Greeting"); // queries inside baseElement (which usually means document.body)
  screen.getByText("Greeting"); // queries inside document.body
});

Which one should you use

I don't think this matters much and you should be fine either way. That said, the creator of the library advocates for screen and also mentions you should avoid using the container or baseElement render options.


Useful links

  • why you should use screen
  • screen docs
  • render options
like image 158
Doug Avatar answered Sep 16 '22 20:09

Doug


The view is just the result of render, so in the docs we see:

The render method returns a promise which resolves with an object that has a few properties:

...queries#

The most important feature of render is that the queries from DOM Testing Library are automatically returned with their first argument bound to the results of rendering your component.

So you have your objected generated by your App, that you can query. screen is

screen#

All of the queries exported by DOM Testing Library accept a container as the first argument. 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 (using the within functionality).

So querying here queries the entire body always.

like image 36
kabanus Avatar answered Sep 16 '22 20:09

kabanus