Solution to the Exercise

Understand one of the possible solutions to the last exercise.

We'll cover the following

Exercise recap

In the last lesson, we tested and implemented the getTasks and updateTask functions. This was possible thanks to the jest-fetch-mock library, which mocked out the fetch function for us. Your task was to do the same for the createTask function.

Solution

Here is the test code:

describe('#createTask', () => {
    it('must create tasks', async () => {
        fetch.mockResponseOnce(JSON.stringify({id: 1, label: 'Do this', completed: false}));

        const result = await createTask('Do this');

        expect(result).toEqual({id: 1, label: 'Do this', completed: false});
        expect(fetch).toHaveBeenCalledWith(expect.stringMatching(/tasks/), {
            method: 'POST',
            body: JSON.stringify({label: 'Do this', completed: false})
        });
    });
});

As you can see, there are no surprises. Firstly, we set the return value for fetch to a “newly created” task. Then, we call the createTask function with the same task name. We expect it to return the same data returned by fetch and call fetch with a POST request to /tasks. Here is the code for the function itself:

export const createTask = async (taskName) => {
    const newTask = {
        label: taskName,
        completed: false
    };
    const result = await fetch(ROOT, {
        method: 'POST',
        body: JSON.stringify(newTask),
    });
    return result.json();
};

Get hands-on with 1400+ tech skills courses.