There are many types of components that can be unit tested. We have routes, async functions, timer functions, states, redux, lifecycle methods, charts, etc that needs to be unit tested.

In this series of tutorial, we will look into testing all these aspects mentioned above, so that you get complete picture of unit testing in React. By the end of the tutorial series, you will be a developer who can write test cases easily and can start working in Test Driven Development (TDD) mode.

One of the main reason the developer do not write test case is because writing correct and useful test case is hard. When you look into the examples in test libraries like jest, they are very simple. They test some simple functions. But in reality, when working on real projects, things are not always ideal. You need to write code that is testable. You need to know which code needs to be tested and which code would be better off with snapshot testing or integration testing.

Setting up the environment using create-react-app

If you are using create-react-app, then it comes up with default configuration to write the unit test cases using jest. To create a new application using create-react-app, run the command

create-react-app sample-app

If you are using npx, then run the command

npx create-react-app sample-app

It will create a new folder called "sample-app".

You can view the sample test in the file sample-app/src/App.test.js .

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);

You can run the above test using the command

yarn test

Setting up the environment without create-react-app

If you are not using create-react-app, then you need to install the dependencies manually. Because jest is a independent library for testing, it does not require react to be installed. You can get started with testing using jest by simply creating a module and installing jest as dependency and writing the test case.

You can create a sample project using webpack, and integrate jest into it, although it has its own unique challenges as webpack is deeply integrated with the application. Although the scenario where you will create a custom boilerplate for react from scratch with webpack is rare, but if you do so, then you can learn more about integrating jest with the webpack here