Member-only story
Module Mocking in Jest
Exports and module factories and mock implementations — oh my!

When testing JavaScript code using Jest, sometimes you may find yourself needing to mock a module. Whether it’s because the module or the functions it exports are irrelevant to the specific test, or because you need to stop something like an API request from trying to access an external resource, mocking is incredibly useful. There are, however, several different approaches to module mocking in Jest, which can lead to confusion. Which approach is the right one for any given scenario?
In this article, we’ll walk through various scenarios using ES6 modules with named exports, a default export, or a mix of both.
ES6 Module Exports
ES6 modules provide two different ways to export methods and variables from a file: named exports and default exports. Any given file could have one or more named exports, one default export, or both named exports and a default export.
The way you mock your module in Jest will depend on the way in which data is exported from the module.
Module Mocking Scenarios
When testing a module in Jest, there are several possible module mocking scenarios that you might run into:
- Not needing to mock anything at all
- Automatically mocking the module
- Mocking the module using the module factory method
- Mocking the module using the module factory method and mock implementations
- Partially mocking some methods in the module but not all the methods
Let’s explore each of these possibilities below.
Mocking Named Exports
First, let’s consider how we would test a module that only exports named exports. We’ll start with a fictional utils.js
file that contains three methods that are all exported as named exports:
export const method1 = () => 'You have called Method 1'export const method2 = () => 'You have called Method 2'export const method3 = () => 'You have called Method 3'