Module Mocking in Jest

Exports and module factories and mock implementations — oh my!

Tyler Hawkins
codeburst
Published in
10 min readSep 30, 2020

--

Jest logo

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:

--

--