Liberate your UI Development: Setup a Mock API

Do you ever hear any of these statements at your workplace:

  • I can’t. The API is down again.
  • I’m blocked. I’m need updates to the API before I can continue.
  • I wasn’t able to get much done. The VPN was down, and I couldn’t connect to the API.
  • I spent half my day getting the APP into one, specific state over and over again. Shoot me.

Dependence on a functioning API is a drag. It slows development down. It forces you work where you have a network connection. It can make getting your app into a specific state really difficult. And, if the API goes down, you’re hosed.

You can solve all these problems by using a Mock API. A Mock API is a utility that intercepts XHR and/or fetch requests, and returns mock data. By introducing a Mock API to your application you will:

  • never be blocked by a broken or unavailable API again.
  • never need to wait for feature updates to your API before beginning development. You can work in parallel with the API team, once you agree on an API contract with them.
  • make it easy for you to simulate specific states in your application.

Sound awesome? It is!

A Mock API in Four Steps

Setting up a Mock API is super easy. Here’s how you do it:

  1. Install a fetch and/or XHR mock utility — what you install will depend on the needs of your app.
  2. Create mock data.
  3. Configure API Mocking.
  4. Configure your application to turn API mocking on and off.

One bit of terminology: Fixture. A fixture is a tool that allows you to work with sample data. We’ll use the term fixtures to refer to both the Mock API, and the data it returns.

The Sample App

In this tutorial, we’ll take an existing application — Contact Manager — and add fixtures to mock its API. Contact Manager only uses fetch.. We’ll use fetchMock, a utility for mocking http requests made using fetch.

Contact Manager uses the users resource of the publicly available JSONPlaceholder API. You can see https://jsonplaceholder.typicode.com/ for more details.

You can clone the app from here: https://github.com/joe-crick/contact-manager. Once you’ve cloned it, download the dependencies by running:

yarn or npm i

Installation

Installation of fetchMock is standard:
yarn add fetchMock -D or npm i fetchMock -D

Note: The -D flag saves the module as a devDependency.

Create Mock Data

Your mock data must match the data definition for results returned from your API. Contact Manager utilizes one resource — users. The users resource returns an array of user objects.

First, we’ll create a folder called fixtures to hold both the fixture data and the API mocks. Inside that folder, we’ll create a file called users.js. users.js will contain a small set of user data that matches the form of the data defined by the users resource:

https://medium.com/media/20c549875e90f01ad5743f532116e4bc/href

Configure API Mocking

Next, we’ll add a file called fixtures.js. This is the file where we’ll define what resources our fixtures will mock:

https://medium.com/media/f1de89bc85e81eb8bd04d97bdeeef9ad/href

There are three things required to create a simple API mock:

  1. HTTP method
  2. URI matcher
  3. Response data

HTTP method
fetchMock provides mocking for all HTTP methods (GET, POST, PUT, &c.). To work with a particular method, just call it off the fetchMock object — e.g., fetchMock.get, or fetchMock.post.

URI Matcher
fetchMock also has several different ways you can match a resource URL, including:

  • string literals
  • globs
  • regular expressions
  • and more…

Above, I’ve used regular expressions.

Response Data
We imported the response data we created from users.js. For the GET call to users, we return all the users. For the response from a PUT to update users, we return the first user.

Specific Application States
Implementing a mock API gives you full control over the responses your mock API returns. This is very powerful. For example, it can help you more easily develop your application for specific cases — unique application states and errors.

Let’s walk through an example of how to do this using an error state. In the fixtures folder, add a file called error-fixtures.js.

https://medium.com/media/88ddb0d38b5c87f404cdfb7ef4611250/href

fetchMock allows you to pass in a Response object as its return value. By passing in a Response object with a 500 status, we can generate a server error.

Now, whenever you want to test how your application will respond to an API error on user update, you can do so easily. With this setup, an error will be generated each time you try to update a user.

For full details on how to work with fetchMock, see its documentation.

Configure your application to turn API mocking on and off

The final step in the process is configuring your application so that you can easily turn fixtures on and off. There are lots of ways to do this. We’ll take a simplified approach. Under the fixtures folder, create a file called set-fixtures.js.

https://medium.com/media/9893b773eceed36a1290f112b316d250/href

The code above sets a function, toggleFixtures, on the window object that allows you to easily turn fixtures on or off. toggleFixtures relies on an item, fixtures, set in localStorage. If the fixtures item is true, we turn fixtures on, and vice versa. Finally, all of this can only happen if the environment is not production.

Other Options

fetchMock is great if your application only uses fetch. If you need something else — or something in addition — there are other options. Here are a few:

  • can-fixture is a utility produced by the folks at Bitovi. They develop the CanJS and DoneJS frameworks. can-fixture is designed to work with XHR. You can find more information here: https://canjs.com/doc/can-fixture.html
  • xhr-mock is another utility that mocks XHR. It’s developed by James Newell. You can find more information on xhr-mock here: https://www.npmjs.com/package/xhr-mock.

GraphQL

Summary

Creating a mock API for your application enables you to build UI components and features without a backend implementation. This:

  • liberates your UI development from backend dependencies and issues.
  • makes it easy to simulate specific situations in your application.
  • allows you to work on and test your application offline.

Liberate your UI Development: Setup a Mock API was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: