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?
TLDR; They are very often the same thing.
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
});
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.
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.
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