Jest

2021-07-09 hit count image

create-react-app uses Jest for the testing. So, let's see how to use Jest.

create-react-app series

This blog post is a series. You can see other blog posts of the series on the list.

Outline

Testing is one of the prerequisites for developing and maintaining services. Testing reduces the time to check all functions, prevent bugs, or prevent the same bug happen again. And when you modify a code, Testing can help you find side effects of the code or detect unexpected behavior.

So, Test code is important in developing software. And almost programming languages have testing frameworks. JavaScript has Mocha, Jasmine, Karma, etc of the testing frameworks, and Jest is also one of the JavaScript testing libraries.

create-react-app basically uses Jest for testing. In this blog post, I will introduce the features and usage of Jest.

Jest features

Jest is a test framework developed and maintained by Facebook. it’s a JavaScript test framework, so you can use it for TypeScript, Node, Angular, Vue, etc.

Jest is focused on simple for anyone to test easily. In addition to simplicity, Jest has features like below.

Zero configuration

Many test frameworks have many configurations for testing, but Jest supports Zero configuration to solve this problem that people can’t start to test easily because of too many settings.

Snapshot

Sometimes, we need to test a very big Object in JavaScript. At this time, it’s difficult to check the value is correct or not. Jest provides the Snapshot feature for these situations. We can take and save a snapshot of the big Object, and if the value is changed in the object, Jest compares it with the snapshot and shows an error. In React, Snapshot is normally used for testing the rendered components.

Isolage

Test codes in Jest are completely isolated, and don’t affect each other. These fully isolated tests enable concurrent execution, and concurrent tests reduce the overall test time.

Simple API

Jest is focused on the simple, so the provided API is also very simple. Also, we can simply check the code coverage with –coverage option.

How to use

Let’s see how to use Jest. You can see the source code that is introduced in this blog post on GitHub.

First, we need to JavaScript project for Jest. Create a folder to exercise Jest, and execute the command below to prepare a JavaScript project.

# mkdir jest-example
# cd jest-example
npm init

When you execute the command above, you can see many questions, just press Enter key to pass them.

After answering all questions with Enter key, you can see package.json file in the folder. Next, create index.js file and index.test.js file for Jest.

In here, index.js file will be used for development, and index.test.js file will be used for testing the index.js file.

Jest installation

Execute the command below to install Jest.

npm install --save-dev jest

After installing, open package.json file and modify scripts section like below.

"scripts": {
  "test": "jest --watch"
},

Execute the command below to excute Jest.

npm run test

We don’t have any test code, so you can see an error on the screen. Let’s add test codes to check the usage of Jest.

toBe

Open index.js file and modify it like below.

const sum = (a, b) => {
  return a + b;
};

module.exports = {
  sum,
};

It’s a JavaScript code that gets two parameters to sum them. Next, open index.test.js file to write the test code, and modify it like below.

const { sum } = require('./index');

describe('test index.js file', () => {
  it('sums a and b', () => {
    let result = sum(1, 2);
    expect(result).toBe(3);
    result = sum(3, 4);
    expect(result).toBe(7);
  });
});

First, we imported the sum from index.js file.

const { sum } = require('./index');

And then, use describe function of Jest to write the description of the test, and pass the callback function includes test.

describe('test index.js file', () => {
  ...
});

We use it function of Jest for the test codes, and write the description of the test code and pass the callback function include test code like describe.

it('sums a and b', () => {
  ...
});

Next, for the test, pass the variable that you want to test in the expect function of Jest, and use toBe to check the value is the same as the expected value.

let result = sum(1, 2);
expect(result).toBe(3);

You can use more simple like below.

expect(sum(1, 2)).toBe(3);

In Jest, we can write the test code by adding the values that we want to check and expectations like above.

After modifying and saving the file, we’ve executed jest --watch command, so Jest recognizes the changed file and executes the test code automatically. And you can see the result like below.

 PASS  ./index.test.js
  test index.js file
    ✓ sums a and b (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.712 s, estimated 1 s

toEqual

If you have studied JavaScript before, you already know Object comparison is difficult in JavaScript.

const temp = {
  name: 'Yakuza',
  age: 20
}

console.log(temp == {
  name: 'Yakuza',
  age: 20
});
// false

Jest provides toEqual function to compare Object. First, open index.js file and modify it like below.


const makeUser = (name, age) => {
  return {
    name,
    age,
  };
};

module.exports = {
  
  makeUser,
};

And then, open index.test.js file and modify it like below.

const { ..., makeUser } = require('./index');

describe('test index.js file', () => {
  ...
  it('makes a person', () => {
    expect(makeUser('Yakuza', 20)).toEqual({
      name: 'Yakuza',
      age: 20,
    });
  });
});

We can test the object by using toEqual like toBe above.

After modifying and saving the file, you can see the result on the screen.

 PASS  ./index.test.js
  test index.js file
    ✓ sums a and b
    ✓ makes a person (1 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.577 s, estimated 1 s

toContain

We can check the array includes the specific value by toContain function.

First, open index.js file and modify it like below.

...

const makeRange = (start, end) => {
  let result = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};

module.exports = {
  ...
  makeRange,
};

The new function will return the array when you pass the start and end values of the array. And open index.test.js file and modify it like below to test this function.

const { ..., makeRange } = require('./index');

describe('test index.js file', () => {
  ...
  it('has 3', () => {
    expect(makeRange(1, 4)).toContain(2);
  });
});

In Jest, we can use toContain function to check the array includes the specific value.

After modifying and saving the file, you can see the result like below.

 PASS  ./index.test.js
  test index.js file
    ✓ sums a and b (1 ms)
    ✓ makes a person
    ✓ has 3

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        0.604 s, estimated 1 s

etc

In addition to the functions introduced here, Jest provides many functions. You can see the functions provided by Jest on the link below.

Code coverage

Let’s see the Jest code coverage. Cancel the current command, and execute the command below.

npx jest --coverage

When you execute the Jest command with the coverage option(–coverage), you can see the code coverage result like below.

 PASS  ./index.test.js
  test index.js file
    ✓ sums a and b (2 ms)
    ✓ makes a person
    ✓ has 3 (1 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 index.js |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        2.703 s

Completed

We’ve seen what Jest is and how to use Jest in this blog post. We’ll use Jest to test create-react-app project later.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts