Creating Reusable Mocks: Continued
Continue the discussion about reusable mocks and testing practices while we further develop the "useTasks" hook.
We'll cover the following...
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:
- Call the hook and extract the
createTaskfunction from its return value. - Call the function with the new task name.
- Verify that the underlying API function was called with the correct argument.
- Verify that the
tasksresult 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 sinceuseTasksis supposed to always load ...