[Jest] - partial mock function in module in Jest P1

Truong Bui

Published on: Last updated:

ts js jest tips

TABLE OF CONTENTS

  1. Problem
  2. Solution

Problem

File name: math.ts
export const add = (a: number, b: number) => a + b;
export const subtract = (a: number, b: number) => a - b;
export const multiply = (a: number, b: number) => a * b;
File name: do-math.ts
import { add, multiply, subtract } from './math';

export const complexFormula = (a: number, b: number) => {
	const sum = add(a, b);
	const mul = multiply(a, sum);
	return subtract(mul, b);
};
Now, I want to test the complexFormula function, but I want to mock the add function. How can I do that ?

Solution

File name: do-math.test.ts
import * as math from './math';
import * as doMath from './do-math';

jest.mock('./math', () => {
	return {
		...jest.requireActual('./math'), // keep the original implementation of other functions
		add: jest.fn(),
	};
});


describe('complexFormula', () => {
	const addFunctionSpy = jest.spyOn(math, 'add');
	it('should return correct value', () => {
		addFunctionSpy.mockReturnValue(10);
		const result = doMath.complexFormula(1, 2);
		expect(result).toBe(8);
	});
});
INFO:
You can read more about bypassing module mocks in Jest at https://jestjs.io/docs/bypassing-module-mocks
What happen if complexFormula function is in math file ? In that case jest.requireActual('./math') does not work. I will show you how to do that in the next post.

Hope you find this article useful. If you have any questions, please let me know in the comment section below. 👇