Setup Jest and React Testing Library in a React project | a step-by-step guide

Not way back that I got here throughout with the idea of testing particularly “writing checks”. I used to check every part by working opening browsers and doing every part manually however you’ll be able to’t know what can go flawed whenever you change one thing and normally it does. The purpose is that actual apps want testing to make sure that our options is not going to break unexpectedly. On this tutorial I’ll stroll you thru within the means of organising Jest and React testing library (RTL) for testing React purposes

Word: it is a third article within the collection of organising a React atmosphere from scratch. within the first article, we created a model new React mission from scratch with out utilizing create-react-app, the second article we configured ESLint, Prettier and Husky and we are going to base on this progress to setup a Jest and RTL and write our first check.

Stipulations

  • I’ll assume that you’ve got a react app working and every part we constructed from earlier articles, you can too observe alongside in case you want this text for different functions however notice that it might look completely different than what I’ve
  • VS code: I shall be utilizing Vs code as our code editor however be happy to make use of any of your choice

that is all you want let’s get began

Why testing?
Exams will be boring to put in writing and ineffective in some instances however I can not stress sufficient the significance of testing extensively your utility. how you make sure that your app nonetheless works after including new code? => you write checks, how do you notice bugs that you just by no means although they existed? by writing check. it is suggested that you just check every part you write to have faith that your app is working as anticipated. Testing may be very strictly enforced at many organizations and a few use the Take a look at-driven growth the place checks are written earlier than you implement options

Jest
Jest is an open supply check framework created by Fb and is effectively built-in with React. it have many built-in like snapshot testing, perform mocking, protection assortment and is normally simple to configure and use. on this configuration we shall be utilizing Jest to run all checks we write know which one failed or handed and accumulate protection i.e. inform us traces that aren’t coated/examined in our codebase. study extra about Jest here

React Testing Library
React testing library (RTL) is a light-weight is a testing Library that allow us to check React by simulating how customers will work together with our utility. as talked about Here the official React documentation recommends utilizing RTL to allow and encourage writing checks that use your parts as the tip customers do. study extra about RTL here

in our configuration we shall be utilizing each Jest and RTL however notice that any can be utilized on it is personal or with different instruments. for higher testing we shall be utilizing React testing Library to search out our parts and manipulate them whereas Jest will decide passing and failing checks and testing protection

This information shall be extra of configuration so I will not cowl a lot about writing checks. for extra about testing React utility test this nice article here

Sufficient with the speaking. let’s get this get together began observe the next steps
from the earlier articles right here is the present

1. Set up React testing library dependencies

  • run the next command to put in RTL dependencies (as dev dependencies)
npm set up --save-dev @testing-library/react @testing-library/jest-dom
Enter fullscreen mode

Exit fullscreen mode

in case you want yarn

yarn add --dev @testing-library/react @testing-library/jest-dom
Enter fullscreen mode

Exit fullscreen mode

  • @testing-library/react: the core dependency that set up react testing library.
  • @testing-library/jest-dom: enable us to make use of customized jest matchers to increase jest with react testing library. there matchers will make your checks extra declarative, clear to learn and to keep up. Extra on this later

2. Set up Jest

  • run the next command to put in jest as a dev dependency
npm set up --save-dev jest jest-environment-jsdom
Enter fullscreen mode

Exit fullscreen mode

in case you want yarn

yarn add --dev jest jest-environment-jsdom 
Enter fullscreen mode

Exit fullscreen mode

  • jest: the core dependency required for Jest to work
  • jest-environment-jsdom: this may enable us to make use of jsdom and we are going to use it along with @testing-library/jest-dom

3. Configure Jest
You may configure Jest by including jest entry within the bundle.json or add a file named jest.config.js within the root folder. To maintain bundle.json clear we are going to use jest.config.js

create a file named jest.config.js within the root folder and add the next code configuration.

Most of jest configured are effectively configured by default however you’ll be able to customise every part by including extra fields on this file. Study extra about all configurations here

module.export = {
    collectCoverage: true,
    collectCoverageFrom: ['src/**/*.{js,jsx}'],
    coverageDirectory: 'protection',
    testEnvironment: 'jsdom',
}
Enter fullscreen mode

Exit fullscreen mode

perceive this configuration

  • collectCoverage: permits gathering protection
  • collectCoverageFrom specifies information to gather protection from this shall be from information information in all .js and jsx from src folder
  • coverageDirectory specifies folder jest will put protection information
  • testEnvironment The check atmosphere that shall be used for testing notice that we’re setting it to jsdom and this shall be coming from @testing-library/jest-dom and jest-environment-jsdom packages we put in earlier.

4.Combine Jest with React testing Library

  • within the root folder create a file named jest.setup.jsenter the next line of code
import '@testing-library/jest-dom'
Enter fullscreen mode

Exit fullscreen mode

which means that we’re importing every part from @testing-library/jest-dom bundle

  • within the jest.config.js file we created earlier add one other discipline of setupFilesAfterEnv and set it is worth to be ['<rootDir>/jest.setup.js'] this may inform jest for each check we write it can load configuration from jest.setup.js i.e. use React testing libraly
    your jest.config.js ought to seem like this
modules.export = {
    collectCoverage: true,
    collectCoverageFrom: ['src/**/*.{js,jsx}'],
    coverageDirectory: 'protection',
    testEnvironment: 'jsdom',
        setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
}
Enter fullscreen mode

Exit fullscreen mode

5.Combine Jest with ESLint
Within the second article we setup ESLint and by default in case you use Jest Eslint will give errors as a result of we do not import some features that we use in Jest and eslint would not settle for that observe the next steps

  • Run the next command to put in eslint-plugin-jest which is able to make Eslint recognise Jest code
npm set up --save-dev eslint-plugin-jest
Enter fullscreen mode

Exit fullscreen mode

yarn add --dev eslint-plugin-jest
Enter fullscreen mode

Exit fullscreen mode

  • within the eslintrc.json add "jest" within the plugins array
  • within the eslintrc.json add "plugin:jest/really useful", within the extends to make use of really useful jest syntax
  • within the eslintrc.json within the env entry add "jest/globals": true

Your eslintrc.json ought to find yourself wanting like this

{
    "env": {
        "browser": true,
        "es2021": true,
        "jest/globals": true
    },
    "extends": [
        "plugin:react/recommended",
        "plugin:jest/recommended",
        "airbnb",
        "prettier"
    ],
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": "newest",
        "sourceType": "module"
    },
    "plugins": ["react", "jest"],
    "guidelines": {
        "no-underscore-dangle": 0,
        "import/extensions": [
            "error",
            "ignorePackages",
            {
                "js": "always",
                "jsx": "always"
            }
        ]
    }
}
Enter fullscreen mode

Exit fullscreen mode

6. Including testing scripts
within the bundle.json within the script object add the next scripts

scripts:{
... //scripts you have already got
check: "jest",
protection: "jest --coverage"
}
Enter fullscreen mode

Exit fullscreen mode

check: "jest": will discover all our check to which whicha passing and failing
protection: "jest --coverage": will run our checks too and likewise accumulate our protection

That is all of the configuration now you’ll be able to write some checks

Writing checks
By convection we create a folder known as check or __test__ within the folder you’ve information you need to check and checks can have title foo.check.js or bar.check.js

  • within the src folder create a check folder and add App.check.jsx to check App.jsx and the next code
import { render, display } from '@testing-library/react';
import React from 'react';
import App from '../App.jsx';

describe('App checks', () => {
    it('ought to incorporates the heading 1', () => {
    render(<App />);
        const heading = display.getByText(/Hiya world! I'm utilizing React/i);
        anticipate(heading).toBeInTheDocument()
    });
});
Enter fullscreen mode

Exit fullscreen mode

  • run check by working npm run check and it ought to go

on this check we’re testing that we’ve textual content Hiya world! I'm utilizing React in our web page and this could go as that is the textual content we utilized in article 1

There you’ve it that is how we setup Jest and React Testing Library to check React purposes

For reference of code talked about on this article test this GitHub repository

Add a Comment

Your email address will not be published. Required fields are marked *