Integrating Unit Tests with Jest in React

Tiempo de lectura: 2 minutos

Today we are going to learn how we can integrate tests with Jest that allow us to test the React components created.

The first thing we have to do is install Jest:

npm install --save-dev jest

Install testing-library/jest-dom:

npm install --save-dev @testing-library/jest-dom

We installed ts-jest

npm install --save-dev ts-jest

We installed:

 npm install --save-dev babel-jest

We will install React testing library:

npm install --save-dev @testing-library/react

If we use TypeScript:

npm install --save-dev @testing-library/react @types/react-dom @types/react

Moreover for typescript:

npm i --save-dev @types/jest

Now let’s create the folder structure for our Jest tests:

Create only folders, no need to add scripts. In the next steps, we will add the scripts.

And let’s initialize jest:

npm init jest@latest

First ask if you want to include the command test within package.json. Put Yes

Then it asks if we have TypeScript, if so put Yes and if not No

The environment for testing is used node.

We will not ask if we want coverage reports, in my case I do want to generate the coverage file and select v8.

If I want to clean up contexts, results… after each test mark Y.

Finally it creates the configuration in jest.config.ts

Returns will have to be installed:

npm install --save-dev ts-node

Returns only the HTML translated, without any added.

Returns only the HTML translated, without any added.

If we get an error on module.exports from .eslint, add this to the file .eslintrc.cjs

  env: { browser: true, es2020: true, node: true, commonjs: true, jest:true},

If we use TypeScript inside the file tsconfig.json we add in compilerOptions:

Now let’s implement a first Unitary test of a button component:

To test this element, we will create within tests/unit/components the file Button.test.js

If we want to nest different tests, we can use the describe function:

And now we can execute the test:

npm run test

Leave a Comment