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

Truong Bui

Published on: Last updated:

ts js jest tips

TABLE OF CONTENTS

  1. Problem
  2. Solution

Problem

Continuing from the previous post , the complexFormula function has now been moved to the math file.
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;

export const complexFormula = (a: number, b: number) => {
	const sum = add(a, b);
	const mul = multiply(a, sum);
	return subtract(mul, b);
};
With the same requirement, we need to test complexFormula function, but I want to mock add function.

Solution

Before go to solution, I want illustrate the relationship between math module and add function.
get 'add' property configuration of math module
As you can see, the value is the function (a, b) => a + b so to mock add function, all we need to do is override value using Object.defineProperty
File name: math.test.ts
import * as math from './math';

const mockAddFn = jest.fn();

describe('complexFormula', () => {
	beforeEach(() => {
		Object.defineProperty(math, 'add', {
			value: mockAddFn,
	});
});

	it('should return correct value', () => {
		mockAddFn.mockReturnValue(10);

		const result = math.complexFormula(1, 2);
		expect(result).toBe(8);
	});
});
But to be honest, for easy way I often assign the mock function directly to the module.
File name: math.test.ts
import * as math from './math';

const mockAddFn = jest.fn();

describe('complexFormula', () => {
	beforeEach(() => {
		(math as any).add = mockAddFn; // we need to cast to any because add is readonly
	});

	it('should return correct value', () => {
		mockAddFn.mockReturnValue(10);

		const result = math.complexFormula(1, 2);
		expect(result).toBe(8);
	});
});
It's easy, right ? 😎

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