In recent (June '20) articles on "how to use react testing library" it's not rare to find a setup like the following:
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
describe('App', () => {
test('renders App component', () => {
render(<App />);
screen.getByText('Search:');
});
});
Where the global variable screen is being used to access the context of whatever is being rendered in a specific test case. I seem to struggle finding motivations behind this choice.
A global stateful variable that mutates between test cases really seems concerning to me, I think it sits quite at the opposite of "side effects free" code. I also find this unnecessary as someone could simply do:
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
describe('App', () => {
test('renders App component', () => {
const screen = render(<App />);
screen.getByText('Search:');
});
});
In this article then the advantage seems to be the "not need to destructure":
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.
something you could achieve by simply not destructuring imho.
Finally, A global variable that is magically able to resolve the context of whatever is being rendered seems to unnecessarily obfuscate the "how the code works". While it might appear to be primarily opinion based, explicit programming is something I would always prefer.
It'd be great if someone could clarify