3. Mocking Modules

This section of The Jest Handbook is dedicated to improving your understanding of Jest’s module mocking functionality

You will learn to:

  • intercept CommonJS imports and ESM default and named imports and exports
  • identify the gotchas in JavaScript module mocking
  • refactor code to expose internal functionality in order to spy on it
  • create partial mocks for ESM and CommonJS modules

What is module mocking?

In order to scale a codebase, developers will start splitting functionality into modules.

The idea behind a module is that it implements a chunk of functionality. Another characteristic is that it should “hide” the details of this implementation from any of its consumers.

What this means in terms of testing is that the functionality of modules that are imported into a module under test are not actually part of its “unit of code”. Hence dependencies should be mocked to avoid testing them again.

This section looks at how to achieve this with Jest in CommonJS and ESM module formats.

Jump to table of contents