Search⌘ K
AI Features

Creating Reusable Mocks: Continued

Explore how to complete testing and implement a custom React hook named useTasks with Jest mocks. Understand how to mock API calls, test task creation and toggling, and manage hook state with useState and useEffect to ensure reliable unit tests.

Where we left off

In the last lesson, we wrote the very first test for the useTasks hook. This hook is supposed to be a bridge between APIs and the TaskList component. Our first test verified that useTasks loads the tasks from the API. To do this, we had to mock the API functions. Firstly, we did it manually (using the jest.mock function with a generator function). Then, we did it automatically (using the __mocks__ folder and jest.mock function). Now, we will complete the testing and implementation of useTasks.

it('must create tasks')

Once we get to the loading tasks, it is time to think about creating new ones. As we agreed before, the API for the useTasks will be as follows:

const [tasks, {createTask, toggleTask}] = useTasks();

In our test, we must:

  1. Call the hook and extract the createTask function from its return value.
  2. Call the function with the new task name.
  3. Verify that the underlying API function was called with the correct argument.
  4. Verify that the tasks result was updated with the new task.

Let’s begin with rendering the hook and extracting the function:

it('must create tasks', async () => {
    const {result, waitForNextUpdate} = renderHook(() => useTasks());
    await waitForNextUpdate();

    const [_, {createTask}] = result.current;
});

The waitForNextUpdate() call is required since useTasks is supposed to always load ...