DEV Community

vinayak
vinayak

Posted on • Originally published at itsvinayak.hashnode.dev on

3 2

Writing Unit Tests in Javascript Using JEST

Jest is a JavaScript testing framework that is focused on simplicity. It allows you to write tests with an accessible, familiar, and feature-rich API that gives you test results quickly.

Image description

  • It helps to write a fast and safe test case, which runs parallel.
  • it can generate code coverage by adding the flag --coverage
  • it allows easy mocking of functions and APIs.

Installing 🔌 JEST

Using npm

npm install --save-dev jest

Enter fullscreen mode Exit fullscreen mode

Using yarn

yarn add --dev jest

Enter fullscreen mode Exit fullscreen mode

Writing Simple Test

create a node project using npm

npm init

Enter fullscreen mode Exit fullscreen mode

Folder Structure 🗂

Screenshot from 2022-06-07 09-57-58.png

let's put some sample functions to test in index.js

function sum(a, b) {
  console.log("adding values ", a, " ", b);
  return a + b;
}

function diff(a, b) {
  console.log("diff between values ", a, " ", b);
  return a - b;
}

function mul(a, b) {
  console.log("multiplying values ", a, " ", b);
  return a * b;
}

function div(a, b) {
  console.log("dividing values ", a, " ", b);
  return a / b;
}

function mod(a, b) {
  console.log("modulus values ", a, " ", b);
  return a % b;
}

module.exports = {
  sum: sum,
  diff: diff,
  mul: mul,
  div: div,
  mod: mod
};

Enter fullscreen mode Exit fullscreen mode

now, we need to install jest and do the configuration in the package.json file.

Screenshot from 2022-06-07 10-06-55.png

Inside the scripts key, we define a jest test logic.

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

Enter fullscreen mode Exit fullscreen mode

Time to write some test, to ensure correct working of our functions. Inside index.test.js import our file.

const cal = require('../index');

Enter fullscreen mode Exit fullscreen mode

writing test 💻 for the sum function

const cal = require('../index');

test('adds 1 + 2 to equal 3', () => {
  expect(cal.sum(1, 2)).toBe(3);
  expect(cal.sum(1, 2)).not.toBe(4);
  expect(cal.sum(1, 2)).toBeGreaterThan(2);
  expect(cal.sum(1, 2)).toBeLessThan(4);
  expect(cal.sum(1, 2)).toBeCloseTo(3);
  // Testing datatype
  expect(typeof cal.sum(1, 2)).toBe("number");
});

Enter fullscreen mode Exit fullscreen mode

Running the test from terminal

npm run test

Enter fullscreen mode Exit fullscreen mode

Screenshot from 2022-06-07 10-36-41.png

we run our first test, everything works fine. but the value of a, b is hardcoded, we will use Math.floor(Math.random() * 11) function for generating a and b. For Repeating SetUp we will use the beforeEach hook, Which is used if we have some work we need to do repeatedly for many tests.

beforeEach(() => {
  a = Math.floor(Math.random() * 100);
  b = Math.floor(Math.random() * 100);
});

Enter fullscreen mode Exit fullscreen mode

Complete Testing Code

const cal = require('../index');

let a;
let b;

beforeEach(() => {
  a = Math.floor(Math.random() * 100);
  b = Math.floor(Math.random() * 100);
});

test(" testing sum " + a + " " + b + " function ", () => {
  expect(cal.sum(a, b)).toBe(a + b);
  expect(cal.sum(a, b)).not.toBe(a + b + 1);
  expect(cal.sum(a, b)).toBeGreaterThan(a + b - 1);
  expect(cal.sum(a, b)).toBeLessThan(a + b + 1);
  expect(cal.sum(a, b)).toBeCloseTo(a + b);
  // Testing datatype
  expect(typeof cal.sum(a, b)).toBe("number");
});

test(" testing diff " + a + " " + b + " function ", () => {
  expect(cal.diff(a, b)).toBe(a - b);
  expect(cal.diff(a, b)).not.toBe(a - b + 1);
  expect(cal.diff(a, b)).toBeGreaterThan(a - b - 1);
  expect(cal.diff(a, b)).toBeLessThan(a - b + 1);
  expect(cal.diff(a, b)).toBeCloseTo(a - b);
  // Testing datatype
  expect(typeof cal.diff(a, b)).toBe("number");
});

test(" testing mul " + a + " " + b + " function ", () => {
  expect(cal.mul(a, b)).toBe(a * b);
  expect(cal.mul(a, b)).not.toBe(a * b + 1);
  expect(cal.mul(a, b)).toBeGreaterThan(a * b - 1);
  expect(cal.mul(a, b)).toBeLessThan(a * b + 1);
  expect(cal.mul(a, b)).toBeCloseTo(a * b);
  // Testing datatype
  expect(typeof cal.mul(a, b)).toBe("number");
});

test(" testing div " + a + " " + b + " function ", () => {
  expect(cal.div(a, b)).toBe(a / b);
  expect(cal.div(a, b)).not.toBe(a / b + 1);
  expect(cal.div(a, b)).toBeGreaterThan(a / b - 1);
  expect(cal.div(a, b)).toBeLessThan(a / b + 1);
  expect(cal.div(a, b)).toBeCloseTo(a / b);
  // Testing datatype
  expect(typeof cal.div(a, b)).toBe("number");
});

test(" testing mod " + a + " " + b + " function ", () => {
  expect(cal.mod(a, b)).toBe(a % b);
  expect(cal.mod(a, b)).not.toBe(a % b + 1);
  expect(cal.mod(a, b)).toBeGreaterThan(a % b - 1);
  expect(cal.mod(a, b)).toBeLessThan(a % b + 1);
  expect(cal.mod(a, b)).toBeCloseTo(a % b);
  // Testing datatype
  expect(typeof cal.mod(a, b)).toBe("number");
});

Enter fullscreen mode Exit fullscreen mode

Screenshot from 2022-06-07 11-03-35.png

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (4)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Good introduction really wish more developers would learn testing at the start so that its easier down the line.

Collapse
 
itsvinayak profile image
vinayak

Thanks ☺️

Collapse
 
leandroandrade profile image
Leandro Andrade

Hi, congrats. Jest is a really good test framework but I'd like to suggest starting using Node Tap. Different Jest which changes global objects, Node Tap is simple and lightweight.

Collapse
 
itsvinayak profile image
vinayak

Thanks, sure will try node tap

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay