Jest How to test modules and single functions with examples
Jest is a testing framework to test different javascript components.
This tutorial explains how to test and mock entire modules and single functions
First, let’s define a single function
add.js
export const add = (a, b) => a + b;
Let’s define a Module
import { add } from "./add";
export const sum = (a, b) => add(a + b);
How to Mock entire modules in javascript using Jest
the calculator is a module that calls other named functions from other files.
To mock the entire module automatically, use jest.mock() function
jest.mock('./calculator');
import { jest } from "@jest/globals";
jest.mock("./calculator");
import { add } from "./add";
import { sum } from "./calculator";
test("calculator tests", () => {
const value = sum(1, 2);
expect(value).toEqual(3); // Success!
});
How to Mock single function from modules in javascript using Jest
To mock a single function First, Create a spy of the function using jest.spyon call spy.mockImplementation() method.
test the method is called using the toHaveBeenCalled method
Here is an example test case file
import { jest } from "@jest/globals";
import * as addObj from "./add";
import { sum } from "./calculator";
test("calculator test single test", () => {
const addSpy = jest.spyOn(addObj, "add");
addSpy.mockImplementation();
expect(addSpy).toHaveBeenCalled();
});