Ganpati
How to start with test cases in React using Jest?

How to start with test cases in React using Jest?

11 June, 2021 by img Prachi Shah in ReactJs Development
How to start with test cases in React using Jest?

How to start with test cases in React using Jest?

What exactly is React JS?

It is an open-source JavaScript library created by Facebook and is used for managing the view layer for mobile and web applications. It is possible to present it on the server-side as well as the client-side. React JS helps simplify the process of mobile application development since the code that has been written at the time of website development can be used once again for creating a web app. React JS is ideal for continuing large amounts of information.

 

What is Jest?

This particular framework has been ranked as the most popular JavaScript testing framework by the stateofjs survey. Facebook has created jest, and the main emphasis with this framework happens to be on simplicity. It offers decent cross-browser support and is used on a wide scale with Selenium for automated testing.

An integrated framework is provided by Jest, which does not need any experience when it comes to the configuration. This tool is all set to use, and it would be possible to set it up instantaneously by running the command-

npm install –save-dev jest

The pros:

  • One can consider Jest to be an exceptionally well documented and quick performing testing framework.
  • A powerful developer tooling is provided by Jest with reduced error-prone code.
  • It is also possible for this framework to execute visual regression tests. It captures screenshots for doing this. During the development of an application by using React JS, this particular feature is quite useful for preventing UI bugs. This is done by recording the rendered component’s screenshot and comparing it afterward with components that have been rendered in the future. It is possible to update the screenshots with the addition of new features.

 

The cons

  • Not much tooling or libraries are supported by Jest as compared to Jasmine and other frameworks.
  • Individuals who are not comfy with this framework have asserted that it is difficult to learn Jest.
  • For bigger snapshot files, snapshot testing is not possible with Jest.

 

Can Jest be considered to be the best JavaScript testing framework?

Your requirement will figure out whether it will be better to use Jasmine or Jest for your project. In case the project needs debugging the test cases in an IDE that is not supported by Jest, then your best choice would be Jasmine. However, it will be advisable to try out Jest, given that Facebook has been making lots of investments at present on this framework. Moreover, the React developers are also getting a positive experience after using Jest.

 


Also Read: Top 3 JavaScript Testing Frameworks with their Pros and Cons


 

In this blog, we have mentioned about How to start with test cases in React using Jest? Let’s know below :

Prerequisite :

Let’s create sample react application by using following commands:

  • npx create-react-app my-app
  • cd my-app
  • npm start

 

Configuration :

  • Check the react version in the package. Json file (“react”: “^17.0.2”).
  • There are too many libraries available that we can use with Jest for test cases but react OOTB provides “@testing-library/jest-dom” so we are using this for our test cases.
  • If this library not added in package.json you can add by  npm install –save-dev @testing-library/jest-dom
  • @testing-library/jest-dom library provides a set of custom jest matchers that you can use to extend jest. These will make your tests more declarative, clear to read and to maintain.
  • Don’t go with the enzyme library as it’s not compatible with react 16+ version.

 

Usage :

  • Need to import @testing-library/jest-dom in react project setup file once and you are good to go with it.
  • If you create a project with create-react-app then there is one file “setupTests.js” already created under src/ folder with import of this library.
  • If not then create “src/setupTests.js” file with following import.
import "@testing-library/jest-dom";

 

Setup :

  • Before continuing, let’s learn some basics. Some key things are used in the following example, and you’ll need to understand them.

 

1. beforeEach / afterEach

  • We will primarily use function components. However, these testing strategies don’t depend on implementation details, and work just as well for class components too.
  • For each test, we usually want to render our React tree to a DOM element that’s attached to the document. This is important so that it can receive DOM events. When the test ends, we want to “clean up” and unmount the tree from the document.
  • A common way to do it is to use a pair of beforeEach and afterEach blocks so that they’ll always run and isolate the effects of a test to itself
  • You may use a different pattern, but keep in mind that we want to execute the cleanup even if a test fails. Otherwise, tests can become “leaky”, and one test can change the behavior of another test. That makes them difficult to debug.

 

2. act()

  • When writing UI tests, tasks like rendering, user events, or data fetching can be considered as “units” of interaction with a user interface. “react-dom/test-utils provides a helper called act() that makes sure all updates related to these “units” have been processed and applied to the DOM before you make any assertions:

 

import { render, unmountComponentAtNode } from "react-dom";

import { act } from "react-dom/test-utils";

let container = null;

beforeEach(() => {

  // setup a DOM element as a render target

  container = document.createElement("div");

  document.body.appendChild(container);

});

afterEach(() => {

  // cleanup on exiting

  unmountComponentAtNode(container);

  container.remove();

  container = null;

});

act(() => {

  // render components

});

// make assertions

 

 

3. it or test

  • You would pass a function to this method, and the test runner would execute that function as a block of tests.

 

4. describe

  • This optional method is for grouping any number of it or test statements.

 

5. expect

  • This is the condition that the test needs to pass. It compares the received parameter to the matcher. It also gives you access to a number of matchers that let you validate different things.

 

Rendering :

  • Commonly, you might want to test whether a component renders correctly for given props. Consider a simple component that renders a message based on a prop.

 

// Hello.jsx

import React from "react";

const Hello = (props) => {

  var returnStmnt = "";

  if (props.name) {

    returnStmnt = <h1>Hello, {props.name}!</h1>;

  } else {

    returnStmnt = <span>Hey, stranger</span>;

  }

  return <>{returnStmnt}</>;

};

export default Hello;

–  We can write a test for this component like this

 

// hello.test.js

import React from "react";

import { render, unmountComponentAtNode } from "react-dom";

import { act } from "react-dom/test-utils";

import Hello from "./Hello";

let container = null;

beforeEach(() => {

  // setup a DOM element as a render target

  container = document.createElement("div");

  document.body.appendChild(container);

});

afterEach(() => {

  // cleanup on exiting

  unmountComponentAtNode(container);

  container.remove();

  container = null;

});

it("renders with or without a name", () => {

  act(() => {

    render(<Hello />, container);

  });

  expect(container.textContent).toBe("Hey, stranger");

  act(() => {

    render(<Hello name="Mark" />, container);

  });

  expect(container.textContent).toBe("Hello, Mark!");

});

 

Output :

  • Now hit npm test”(script is “react-scripts test”) in the command line and you will get the following output.
pass react with jest test case

 

Finally, you successfully created a test case for react components.

 

Looking for Web & Mobile App Developer?

 

img

Prachi Shah

Prachi Shah is a MEAN Stack Developer at Rlogical Techsoft Pvt. Ltd. She has hands-on experience in MongoDB, AngularJS, NodeJS and having expertise in managing multi-use large complex projects. In her free time, she likes to exploring GraphQL with Nodejs , MongoDB and ReactJS and share her knowledge with others.

Get in Touch

Contact Us

USA

600 E Michigan Ave, Kalamazoo, MI 49007, USA

Robert Armbrister: +1 866 277 2752

Contact Email: usa@rlogical.com
info@sparkbusinessworks.com

UK

5 Kew Road, TW9 2PR, London

Peter Klein: +44 753 859 8026

Contact Email: uk@rlogical.com

INDIA (Head Office)

701 Satkar Complex, Opp Tanishq Showroom,Behind Lal Bungalow, Chimanlal Girdharlal Rd, Ahmedabad, Gujarat 380009

Rahul Panchal: +91 982 460 1707
Contact Email: rahul@rlogical.com

Jatin Panchal: +91 997 420 2036
Contact Email: jatin@rlogical.com

JAPAN

301 1-28-21 Hayabuchi, Tsuzuki-ku, Yokohama-shi, Kanagawa 224-0025, Japan

Charles

Contact Email: japan@rlogical.com

Australia

Suit 3, Level 27, 1 Farrer Place Sydney NSW 2000

Contact Email: australia@rlogical.com