Mock API Requests in React Native with Mirage

Mock your React Native app's API requests so you can develop your app without any backend services.

This is a quickstart guide for people familiar with Mirage. If you're brand new to Mirage, take a look at the Overview.

Step 1: Install Mirage

First, make sure you have Mirage installed:

# Using npm
npm install --save-dev miragejs

# Using Yarn
yarn add --dev miragejs

Step 2: Create a Server alongside your networking code

At the top of App.js, import Server from Mirage, create a server, and start mocking out API endpoints that your code needs:

import React from "react"
import { Text, View } from "react-native"
import { createServer } from "miragejs"

if (window.server) {
  server.shutdown()
}

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

export default function App() {
  let [movies, setMovies] = React.useState([])

  React.useEffect(() => {
    fetch("/api/movies")
      .then((res) => res.json())
      .then((json) => setMovies(json.movies))
  }, [])

  return (
    <View>
      {movies.map((movie) => (
        <Text key={movie.id}>
          {movie.name} ({movie.year})
        </Text>
      ))}
    </View>
  )
}

Note that before we call createServer(), we check to see if one already exists, and if so we shut it down. This is needed so React Native's hot module reloading doesn't cause multiple servers to exist at once.

Now, whenever your app makes an API request, Mirage will intercept and respond to it.

You're ready to continue developing your React Native app, mocking out your API endpoints with Mirage along the way.