THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
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);
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!
});
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();
});
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts