Mocking an API in Javascript Projects

Sometimes when working on an API driven front end application, it may be the case that the API (or a feature of the API) isn’t available yet.

In this instance, it is useful to be able to mock the API to return expected responses so you can implement a feature without having the API available.

Mirage JS is a package that allows you to do this by intercepting HTTP requests your Javascript application makes and returning a mocked response based on the endpoints you define.

Add Mirage to your project

Using NPM:

npm install --save-dev miragejs

Using Yarn:

yarn add --dev miragejs

Create a mock API

//mockApi.js
import { createServer } from "miragejs"

createServer({
  routes() {
    this.namespace = "api"

    this.get("/movies", () => {
      return {
        movies: [
          { id: 1, name: "Inception", year: 2010 },
          { id: 2, name: "Interstellar", year: 2014 },
          { id: 3, name: "Dunkirk", year: 2017 },
        ],
      }
    })
  },
})

As long as your module has been loaded by the application, any requests to /api/movies will now return the mocked data above.

Switching between the real / mock API

A handy way to switch between the real and mock API is to load the mock API module based on an environment variable:

//app.js
if (process.env.API_ENV === 'local') {
  require('./mockApi');
}

Brad Dobson

Software developer, ish

Additional reading
https://miragejs.com/