Mocking a Module

Learn to mock a whole module using Jest.

Starter project

The project for this lesson is similar to the project in the last lesson. The difference is that the Hello component renders the user’s role and name. A second web API call is made to get the user’s role.

The project contains a test to verify that the user’s name is rendered. The test should fail at the moment because the web API calls aren’t yet mocked.

A copy of the project is in the code widget below. Clicking the “Run” button executes the tests.

export default "test-file-stub";
Verifying that the tests fail

In this lesson, we will mock out both functions in data.js.

Understanding Jest’s mock function

A whole module can be mocked using Jest.mock. The syntax is:

jest.mock(modulePath);

To mock data.js in our project, we can use jest.mock("./data"). Note that jest.mock won’t work as expected if placed inside a test function.

test("Should include users name when rendered", async () => {
  jest.mock("./data"); // ❌
  render(<Hello id={1} />); // 😞 - the mock `data` module won't be used here
});

Note also that jest.mock needs to be called before any import statements so that Jest can import the mock module rather ...