Using Jest's Mock Function

Learn to refactor the test from the previous lesson using Jest’s mock function in this lesson.

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