How to install Jest and write Jest test cases in React Js

Unit testing is a best practice which can lead to 40%-85% reductions in production bugs.

Unit testing is a best practice which can lead to 40%-85% reductions in production bugs.

Here i will explain you how we can install jest framework in React and how to write sample test case.

React Js running with Jest framework to write test cases and test application.

Install JEST framework

npm install jest

then go to package.jsonin script we have alias for project essential commands

script: { "server": "ng serve", "build": "ng server build" }

Add one more alias for Jest like

script: { "server": "ng serve", "build": "ng server build", "test": "jest" }

now

run npm test

it will run jest application.

if there is no single test case then it will give error of no test cases found.

So create test folder under src folder

Add add.test.js file to write test cases.

Now, write your first test case:

add.test.js

Here we have creted one const add and passing two parameters.

inside arrow function doing addition of parameters.

const add = (a, b) => { a + b }

Jest provide test global variable which accept two parameters, first is name/message/text and section is arrow function.

So at first parameter we will write some description of test case.

For second parameter we will pass arrow function with two numbers as parameters.

test('Should add two numbers', (a, b) => { const total = add(2, 3); });

go to command line and run the test case

npm test

It will return below result with some more information like how many test cases passed, failed, how much time it required:

PASS src/test/add.test.js
Should add two numbers
Test suites: 1 passed, 1 total
Test: 1 passed, 1 total
Snapshots: 0
totaltime: 02 ms
Run all test suites
Done in 1s

Now we check how we can throw error if there is wrong in code logic

So come back to add.test.js file

const add = (a, b) => { a + b }
test('Should add two numbers', (a, b) => { 
  const total = add(2, 3);

  if(total !== 4) { 
   throw new Error('You added 2 and 3. The sum was ${total}. But expected pass condition is 8.');
  }
});

Run above test case

npm test

It will return with 1 test case failed because total is wrong will throw error.

Jest provide some inbuilt methods to manage errors like expect.

Lets see how we can use it.

const add = (a, b) => { a + b };
test('Should add two numbers', (a, b) => { 
  const total = add(2, 3); 
  //if(total !== 4) { 
  //   throw new Error('You added 2 and 3. The sum was ${total}. But expected pass condition is 8.'); 
  //}
  expect(total).toBe(8); 
});

In above code, expect will work same as commented code.
So this way we can define output of our code and test written code after completion of development.

Some benefits of writing test cases are:



You may also like...