...

/

Mocking Arbitrary Imports: Continued

Mocking Arbitrary Imports: Continued

Continue developing the persistence feature, and explore mocks in greater depth.

Where we left off

In the last lesson, we introduced a new persistence feature to our app, and wrote an integration test for it. The test boils down to:

  1. Create a task.
  2. Refresh the page.
  3. Make sure the task is there.
  4. Mark task as completed.
  5. Refresh the page.
  6. Make sure it stays completed.

Next, we will write unit tests that validate each step of that scenario.

API functions

Since we have set up json-server, our trusty backend, we will need to interface with it. I suggest that we first test and create helper functions to make API requests. We will put them in /api/index.js. That means their tests will be under /api/index.test.js. Go ahead and create this file, but leave it empty for now.

Let us take a step back, and think about what we want our API functions to do. To begin with, we will need three functions:

  • createTask: To create a task.
  • updateTask: To update task’s info.
  • getTasks: To get all tasks.

Go ahead and create describe blocks for each of these, and add the (nonexistent) import line:

import {createTask, getTasks, updateTask} from './index';

describe('#createTask', () => {});

describe('#updateTask', () => {});

describe('#getTasks', () => {});

Now comes the interesting part. All of these functions will need to use fetch to make HTTP requests. This means we would have to mock the fetch function. Luckily, there is no need to reinvent the wheel, and we can use the mock that someone else made for us (later we would learn ...