...

/

Mocking Arbitrary Imports

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:

 ...
Access this course and 1400+ top-rated courses and projects.