Im relatively new to JS, and can't figure out what is going on in line 2 of the following template jest test in the latest create-react-app:
test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
Does render always return a function called getByText? Is this destructuring? Why is it used as a method on the third line?
Some familiarity with Jest as a test runner or framework is helpful but not required. Because Jest is pre-packaged with Create React App, you do not need to install it separately.
It is very fast and safe; Jest can run all your tests parallel by ensuring they have a unique global state. To make things quicker and easier, it runs previously failed tests first and then reorganizes the runs of the next tests, which are based on the long test files.
The code example you are asking about is not part of Jest per se. The render
function is provided by React Testing Library, a popular tool for testing React components.
Yes, in line 2, destructuring is used to get the function getByText
. The render
function actually returns an object containing a number of functions that let you inspect the virtual DOM nodes rendered by React.
getByText can be used search for all elements in the rendered virtual DOM that have a text node with text content matching the given regular expression.
In line 3 of your code example, this is used to check if the text “learn react” is contained anywhere in the virtual DOM rendered by the <App />
component.
In line 4, the expect function provided by Jest is used to make an assertion about this text being in the document.
The method toBeInTheDocument of Jest's expect function here is actually provided by another library that sits on top of React Testing Library, jest-dom.
The syntax is called "destructuring". It pulls out methods / properties from objects.
i.e.
// some random object
const obj = {
property1: 'somevalue',
method1: () => "hello"
}
const {property1, method1 } = obj;
console.log(property1, method1());
It can be useful when trying you need to call a method or value frequently from an object and get annoyed by having to call it with the object notation (obj.method()
) repeatedly.
In your example, you could rewrite that as
test('renders learn react link', () => {
const element = render( < App / > );
const linkElement = el.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
and it would be functionally the same.
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