Mocking Arbitrary Imports

Now that you have learned how to create mock objects, we will use these objects to replace arbitrary imports.

More often than not, our code relies on its dependencies. The most obvious one is React. Every file with a React component in it must start with:

import React from 'react';

And so on. Now, suppose that you were making an HTTP request in one of your functions. In other words, your function depends on some HTTP API (whether it is built-in fetch or third party axios). To test such a function, you would have to replace that dependency with a mock.

New feature: DB connection

To make sure you understand mocking, we will apply this knowledge to test and develop yet another feature for our TODO app: saving tasks to a database.

Do not freak out though. We will not develop the backend for it nor set up a real database. We will use a simple tool called json-server (Github) that will create a simple RESTful backend and a JSON database.

To get started, run this command in project root to install json-server:

$ npm i -S json-server

Next, create a file called db.json in project root. This will be our database. To make sure json-server understands what we are trying to do here, add this to db.json:

{
  "tasks": [
    {
      "id": 1,
      "label": "Do this",
      "completed": false
    }
  ]
}

We defined an array called tasks and one sample task. Using this info, json-server will create the following routes for us:

  • GET /tasks: Get all tasks.
  • POST /tasks: Create a new task.
  • PUT /tasks/id: Update an existing task.
  • GET /tasks?completed=true: Get completed tasks only.

And many more, but we will focus on these. To run json-server, add this line to the scripts section of package.json:

"json-server": "json-server --watch db.json --port 3001"

The port is set to 3001 because React is using the 3000 one. With this line in, you are able to run json-server for this project like this:

$ npm run json-server

I also suggest adding the db.json to .gitignore, so you do not clutter the version control system:

db.json

If everything works, you will be greeted with the following message:

PS C:\personal_projects\educative-todo> npm run json-server

> educative-todo@0.1.0 json-server C:\personal_projects\educative-todo
> json-server --watch db.json


  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3001/tasks

  Home
  http://localhost:3001

  Type s + enter at any time to create a snapshot of the database
  Watching...

If you open http://localhost:3000/tasks in your browser, you will see that one sample task that we created earlier:

Now, we have everything ready to implement task persistence in our app! Here is the project so far for reference (Github):

Get hands-on with 1200+ tech skills courses.