How to basic Unit Test with Jest on JavaScript Project

In this article, focus on Unit testing with using jest. The test has many types, its fall into three main categories.

  • unit testing
  • integration testing
  • UI testing

What it can do jest?

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

  • Developer Ready: A comprehensive JavaScript testing solution. Works out of the box for most JavaScript projects.
  • Instant Feedback: Fast, interactive watch mode only runs test files related to changed files.
  • Snapshot Testing: Capture snapshots of large objects to simplify testing and to analyze how they change over time.

How to setting for jest

Install jest in your project using npm.

$ npm i jest -D

Please modify your package.json

{
  "scripts": {
    "test": "jest"
  }
}

Ok, you can use npm jest command, then if you wanna running jest when you saved a file, please use bellow command.

$ npm jest -- --watch

In addition, if you use typescript, check this link.

Basic how to use jest

The next, how to write jest code?

toBe

This is a simple function code.
function.js

const addNumber = (num1, num2) => num1 + num2;
module.exports = addNumber;

function.test.js

const addNumber = require('./function.js');

test('addNumber function exists',()=>{
    expect(typeof addNumber).toEqual('function');
});

// toBe
test('adds 2 + 2 to equal 4',() => {
    expect(functions.add(2,2)).toBe(4);
});

If you wanna check wrong result, you can use.not.

test('adds 2 + 3 to equal 5',() => {
    expect(functions.add(2,3)).not.toBe(4);
});

isNull

Then, same as a another options.

Check null

const returnNull = () => null;
const returnNull = require('./returnNull');

// isNull
test('Should be null',() => {
    expect(functions.isNull()).toBeNull();
});

Its check only null value, so undefined can’t be pass the test.

toBeTruthy or toBeFalsy

Check true or false.

const checkValue = (x) => x;
const checkValue = require('./checkValue');

// toBeFalsy
test('Should be falsy',() => {
    expect(functions.checkValue(undefined)).toBeFalsy();
});

If you check true value, use the toBeTruthy option.

toEqual or toStrictEqual

const createUser = () => {
   const user = {firstName: 'Brad', 'lastName': 'Traversy'};
   return user;
};
// toStrictEqual
test('User should be Brad Traversy object',() => {
    //  If it should pass with deep equality, replace "toBe" with "toStrictEqual"
    expect(functions.createUser()).toStrictEqual({ firstName: 'Brad', lastName: 'Traversy' });
});

The toBe can’t pass the test, so you have to use toEqual or toStrictEqual.

toBeLessThanOrEqual

test('Should be under 1600',() => {
    expect(800 + 700).toBeLessThan(1600);
    expect(800 + 800).toBeLessThanOrEqual(1600);
});

toBeLessThan is number less than 1600 not including 1600. If you use OrEqual, its including 1600 it will be pass the test.

Regular expression

// Regex
test('Should is no I in team',() => {
    expect('team').not.toMatch(/I/i); 
});

Array

Finaly, check the array, include target value. Using the toContain.

// Arrays
test('Admin should be in usernames',() => {
    const usernames = ['john', 'karen', 'admin'];
    expect(usernames).toContain('admin'); // check including admin string in array
});

That’s it.

関連記事