Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic create-react-app jest test explained

Tags:

jestjs

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?

like image 366
alecbaldwin Avatar asked Mar 18 '20 19:03

alecbaldwin


People also ask

Does create React app include Jest?

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.

How does Jest testing work?

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.


2 Answers

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.

like image 110
Patrick Hund Avatar answered Nov 12 '22 02:11

Patrick Hund


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.

like image 42
Jhecht Avatar answered Nov 12 '22 01:11

Jhecht