Search⌘ K
AI Features

Using Jest's Mock Function

Explore how to apply Jest's mock function features to simulate asynchronous and synchronous function behaviors in your React app tests. Understand how to verify mock function calls using Jest matchers to ensure test accuracy and maintainability.

Starter project

The project for this lesson is the completed project from the last lesson. In this lesson, we’ll refactor the test to use Jest’s mock function.

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

export default "test-file-stub";
Half-implemented test

Jest’s mock function

A mock function can be created with Jest using jest.fn(). This function helps us define what should be returned and track its usage.

Update the test in src/Hello/Hello.test.js so that the getUser function is set to Jest’s mock function as follows:

test("Should include users name when rendered", async () => {
  const safe = data.getUser;
  data.getUser = jest.fn();

  render(<Hello id={1} />);

  expect(await
...