Search⌘ K
AI Features

Creating Reusable Mocks

Explore how to write robust unit tests for React hooks by mocking API modules using Jest. Understand how to create reusable mock implementations in __mocks__ folders, use renderHook from @testing-library/react-hooks, and validate asynchronous data fetching. This lesson helps you build scalable, testable code by mastering module mocking strategies.

Interfacing components with API: useTasks hook

Though we have our API helpers written, this is not enough to make tasks persistent. In order to connect the React components and the underlying API functions, create a useTasks hook, which would take the responsibility of polling and updating tasks.

We want it to:

  1. Request the list of tasks on the render.
  2. Make them available to the component as soon as they arrive.
  3. Expose functions to create and toggle tasks.

As always, we start with writing the tests for this hook. Create a folder hooks and a file useTasks.test.js in it. Firstly, we will test that useTasks requests tasks:

import useTasks from './useTasks';

describe('#useTasks', () => {
  it('must request tasks', () => {});
});

Now, think about what we should call the useTasks hook. If you have worked with React for some time, you should know that it is only possible to call hooks from within components, and our test is definitely not a component. Should we develop an entire component to test this hook? The obvious answer is no. We will use @testing-library to render the hook. Specifically, we will use the @testing-library/react-hooks section.

It is not included in CRA by default, so we have to install it:

$ npm i -D @testing-library/react-hooks

Once you have it installed, a couple of very useful functions manifest themselves in your project. Firstly, the renderHook function. It is imported like this:

import {renderHook} from '@testing-library/react-hooks';

And now you can safely call your hook:

const {result} = renderHook(() => useTasks());

renderHook returns an object. In this object, under result.current, you will find the return value from ...