How to mock specific module function in jest?

QJ Li
3 min readSep 21, 2018

--

Mocking a function generally is very easy in jest via jest.fn(). However, if you run into the following scenario which one function in the module is calling another function in the same module, it could be tricky.

For example, you have two functions in a module file.

// helper.jsexport function getFullName(firstName, lastName) {
return firstName + ' ' + lastName;
}
export function greet(firstName, lastName) {
const fullName = getFullName(firstName, lastName);
return `Hey, ${fullName}`;
}

When you are trying to write your jest unit test to test the function greet(), you would assume that you can just mock the getFullName() inside function greet() .

import { getFullName, greet } from './helper';describe('greet', () => {
it('should return greet message with full name', () => {
getFullName = jest.fn().mockReturnValue('mock full name');
const result = greet('QJ', 'Li');
expect(result).toBe('Hey, mock full name');
});
});

However, the result is not what you expect like above. The reason being, getFullName function in the helper.js is a local scope function and override it directly via jest.fn() won’t work here.

There are a few solutions here:

1.) Store all export functions to an object and export by default

Instead of using export function to export each function, do the following:

// helper.jsfunction getFullName(firstName, lastName) {
return firstName + ' ' + lastName;
}
function greet(firstName, lastName) {
const fullName = exportFunctions.getFullName(firstName, lastName);
return `Hey, ${fullName}`;
}
const exportFunctions = {
getFullName,
greet
};
export default exportFunctions;

The trick here is to use exportFunctions.getFullName() in greet() instead of calling getFullName() directly. In this case, in your unit test, you can mock the getFullName() via jest.fn()

import helpers from './helper';describe('greet', () => {
it('should return greet message with full name', () => {
helpers.getFullName = jest.fn().mockReturnValue('mock full name');
const result = helpers.greet('QJ', 'Li');
expect(result).toBe('Hey, mock full name');
});
});

Finally, the result is expected!

2.) Use babel-plugin-rewire to rewire any function

TL;DR, you should get the idea from reading the picture below. The benefit of introducing this npm dependency as devDependency is that you do not need to change the way you export your functions like the №1 solution.

You can directly rewire any functions in the function you want to unit test. Go to the Named and top level function rewiring section in the README to find out more details.

Thanks for reading! 🎊 If you find this helpful don’t forget to give some claps 👏🏻 and feel free to share this with your friends and followers! 🙏If you have some tips to share, feel free to comment below.

--

--

QJ Li

Coding | Lead Myself | Family | Books | Personal CI / CD Daily