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
});
...
Access this course and 1400+ top-rated courses and projects.