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";
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
});
...