DEV Community

Cover image for How to Mock API Calls in React Native and Expo
Sebastian Gedda
Sebastian Gedda

Posted on Originally published at mockifyer.dev

How to Mock API Calls in React Native and Expo

If you've tried to mock HTTP in a React Native or Expo app the way you do on the web, you've already hit the wall: there are no Service Workers. Whatever you choose has to intercept at the HTTP client (fetch / axios) or sit on the network as a mock server the device can actually reach.

Jest stubs are still the right tool for a single module. msw/native is still a good fit when you want typed, in-code handlers for a small API. Mocking also unlocks offline development, stable demos, and deterministic Detox / Maestro / Appium runs.

This post is about the point where hand-written fixtures start to hurt — several backend systems, often several teams — and how to record real traffic once, replay it offline, and share the same mocks across simulators, physical devices, and CI. I built Mockifyer for that larger-app case. It is not a replacement for MSW when you want purely synthetic handler logic, and the approaches can coexist.

Pick the approach that matches the app

These can coexist. Many teams use MSW for one API with hand-written handlers, and record-and-replay when several systems are involved.

Hand-written stubs / Jest mocks. Best for unit tests of a single module where you control the dependency boundary. You invent response shapes. Poor fit for full-app or E2E flows.

MSW (msw/native). Best for a small surface area where you want typed handlers and full control over response logic. The tax is maintenance: every endpoint needs a handler, and that gets expensive as upstream systems grow. Patching fetch also does not automatically intercept axios on React Native, so plan the interceptor per client.

A local React Native mock server. Point the app at http://10.0.2.2:… (Android emulator) or a LAN IP and serve canned JSON. You still hand-author payloads, and physical devices need to reach that server.

Record-and-replay. Best when the app calls many underlying systems across teams: record real traffic once, store JSON under mock-data/, replay offline, switch scenarios, freeze dates, and optionally share via a dashboard-backed store. You need a short recording pass and some Metro (or dashboard proxy) wiring.

Mock fetch in Expo

React Native / Expo apps use @sgedda/mockifyer-fetch, which patches global.fetch. Hybrid storage (device FileSystem plus Metro project sync) also needs Expo FileSystem:

npm install --save-dev @sgedda/mockifyer-core @sgedda/mockifyer-fetch
npx expo install expo-file-system
Enter fullscreen mode Exit fullscreen mode

Optional: npx -p @sgedda/mockifyer-core mockifyer init writes a selective-recording config and prints RN setup when it detects react-native in your dependencies.

Then stub Node built-ins in Metro and enable Hybrid sync so device recordings land in your project mock-data/ folder:

// metro.config.js
const { getDefaultConfig } = require('expo/metro-config');
const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');

const config = getDefaultConfig(__dirname);
module.exports = configureMetroForMockifyer(config, {
  syncMiddleware: {
    projectRoot: __dirname,
    mockDataPath: './mock-data',
    // atlasKey: 't' — optional Metro terminal Atlas capture
    // dashboardKey: 'd' — optional; opens the dashboard in the browser
    // dashboardUrl: process.env.MOCKIFYER_DASHBOARD_URL || 'http://localhost:3002',
  },
});
Enter fullscreen mode Exit fullscreen mode

Init early in your root layout so the first network call is intercepted:

// mockifyer-setup.ts
import {
  setupMockifyerForReactNative,
  isMockifyerReactNativeActive,
} from '@sgedda/mockifyer-fetch';

export async function initializeMockifyer() {
  const result = await setupMockifyerForReactNative({
    isDev: __DEV__,
    mockDataPath: 'mock-data',
    bundledDataPath: './assets/mock-data',
    recordMode: __DEV__ && process.env.EXPO_PUBLIC_MOCKIFYER_RECORD === 'true',
    // MOCKIFYER_MODE / runtimeMode: 'on' | 'manual' | 'launch_client' | 'off'
  });

  if (isMockifyerReactNativeActive(result)) {
    // result.instance.enableMockifyer() / disableMockifyer() when runtimeMode is 'manual'
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

Default MOCKIFYER_MODE when unset is on. For store builds, set MOCKIFYER_MODE=off (alias: disabled) — isDev: false alone is not a hard disable; it still loads the Memory provider with bundled mocks when mode is on. Gate recordMode on __DEV__.

If the app uses axios

Use @sgedda/mockifyer-axios with useGlobalAxios: true, and call setupMockifyer before importing axios. Axios uses a filesystem or dashboard-proxy path — not the Expo Hybrid provider that setupMockifyerForReactNative configures for fetch:

import { setupMockifyer } from '@sgedda/mockifyer-axios';

setupMockifyer({
  mockDataPath: './mock-data',
  recordMode: __DEV__ && process.env.EXPO_PUBLIC_MOCKIFYER_RECORD === 'true',
  useGlobalAxios: true,
  // Optional E2E lane: useLaunchArgumentsClientId: true
});

import axios from 'axios';
Enter fullscreen mode Exit fullscreen mode

MSW and Mockifyer can run in the same app — MSW for a few hand-authored endpoints, Mockifyer for recorded traffic across many systems — as long as you prefer one interceptor per client instance so they do not fight over the same request.

Record selectively, then mix mock and live

The preferred workflow is selective, not “capture everything.”

With recordMode: true, request metadata lands in an ephemeral _scratch scenario. Calls stay on the live API until you activate a mock in the dashboard (clear alwaysUseRealApi / “Always use live API”) or enable paths via domain-path rules (recordResponses / autoMock). Domain-path rules default to allowlist mode (MOCKIFYER_DOMAIN_PATH_RULES_MODE=allowlist): traffic discovers host/path keys with recording off until you opt in.

EXPO_PUBLIC_MOCKIFYER_RECORD=true npx expo start
Enter fullscreen mode Exit fullscreen mode

Start without EXPO_PUBLIC_MOCKIFYER_RECORD=true to replay activated mocks. Endpoints you never activated (or that keep alwaysUseRealApi) continue to hit the real API — that is how you mix mocked and live traffic in one session.

npx expo start
Enter fullscreen mode Exit fullscreen mode

There is a heavy “try it quickly” option for a short demo only — store full bodies and enable record/replay on discovered paths:

EXPO_PUBLIC_MOCKIFYER_RECORD=true EXPO_PUBLIC_MOCKIFYER_RECORD_RESPONSES=true MOCKIFYER_DOMAIN_PATH_RULES_MODE=record_all npx expo start
Enter fullscreen mode Exit fullscreen mode

Or nest the mode on setup config: config: { domainPathRulesMode: 'record_all' }. On Expo, that config form is the reliable client-side switch — the library reads MOCKIFYER_DOMAIN_PATH_RULES_MODE and MOCKIFYER_RECORD_RESPONSES from process.env, and only EXPO_PUBLIC_* values are inlined into the app bundle (official example apps map those aliases in setup). Prefer selective activation for day-to-day work.

Share mocks when the phone cannot reach your laptop

Hybrid + Metro keeps mocks on your machine. That is the right default for solo laptop + simulator work. When a teammate's device, a CI job, a demo build, or a physical phone cannot reach your local mock-data/ folder, run the dashboard against a shared store and proxy app traffic through it.

This is your Redis or SQLite plus a dashboard process the devices can reach — not a hosted multi-tenant cloud product.

The HTTP proxy at /api/proxy requires redis or sqlite, not the default filesystem provider. Redis is the usual choice for multi-device lanes:

# Redis as source of truth for mocks + scenarios (default key prefix mockifyer:v1)
npx @sgedda/mockifyer-dashboard --provider redis \
  --redis-url redis://127.0.0.1:6379 \
  --path ./mock-data \
  --host 0.0.0.0

# Optional: also write recorded mocks to disk for git
#   --redis-mirror-disk   (env: MOCKIFYER_REDIS_MIRROR_DISK=true)
# Optional: if Redis misses, try JSON under mock-data/<scenario>/ before upstream
#   --redis-disk-fallback (env: MOCKIFYER_REDIS_DISK_READ_FALLBACK=true)
# Shorthand for both: --redis-disk-dual
Enter fullscreen mode Exit fullscreen mode

Point the app at it with the RN dashboard preset. URL resolution order is proxyBaseUrl → dashboardBaseUrl → MOCKIFYER_PROXY_URL:

import { initMockifyerForReactNativeDashboard } from '@sgedda/mockifyer-fetch';
import { Platform } from 'react-native';

const dashboardBaseUrl =
  Platform.OS === 'android'
    ? 'http://10.0.2.2:3002' // emulator → host
    : 'http://192.168.1.20:3002'; // physical device / teammate: host LAN IP

await initMockifyerForReactNativeDashboard({
  isDev: __DEV__,
  mockDataPath: 'mock-data',
  bundledDataPath: './assets/mock-data',
  dashboardBaseUrl,
  recordMode: __DEV__ && process.env.EXPO_PUBLIC_MOCKIFYER_RECORD === 'true',
  // Optional: clientId / MOCKIFYER_CLIENT_ID for a client lane
});
Enter fullscreen mode Exit fullscreen mode

iOS Simulator can use http://localhost:3002; Android emulator uses http://10.0.2.2:3002; a physical device needs the host LAN IP, with the dashboard bound to --host 0.0.0.0.

Traffic goes through dashboard POST /api/proxy. Set a lane with MOCKIFYER_CLIENT_ID or the launch argument mockifyerClientId so one device can run trips-empty while another runs trips-many. Redis write caps default to 200 distinct mocks per METHOD+host+path (MOCKIFYER_MAX_MOCKS_PER_PATH; set 0 to disable).

Freeze the date, and lock E2E

Time-dependent UI (“check-in opens today”) needs a stable clock. Use getCurrentDate() from the same package as setup, not new Date(). Fix time via MOCKIFYER_DATE, dateManipulation.fixedDate, or the dashboard Date Config for the active scenario:

import { getCurrentDate } from '@sgedda/mockifyer-fetch';

const today = getCurrentDate(); // respects MOCKIFYER_DATE / scenario Date Config
Enter fullscreen mode Exit fullscreen mode

For local editing, the dashboard usually runs on your laptop, not on the phone:

npm install --save-dev @sgedda/mockifyer-dashboard
npx mockifyer-dashboard --path ./mock-data
# UI at http://localhost:3002
Enter fullscreen mode Exit fullscreen mode

For Detox or Maestro, lock a scenario (and optional client lane) with native launch arguments so every run boots into the same recorded world. Prefer MOCKIFYER_MODE=launch_client so mocks activate only when those args are present:

# Maestro
appId: com.example.app
---
- launchApp:
    arguments:
      scenario: trips-empty
      mockifyerClientId: maestro-test

- assertVisible: "No trips yet"
Enter fullscreen mode Exit fullscreen mode

Keep mocks honest as APIs change

Once mocks live in git (or Redis + a disk mirror), two extras help larger teams:

  • Mock drift — compare recorded mocks to live staging so API renames show up in CI instead of production.
  • Mockifyer Atlas — maps of recorded hops. In Metro Hybrid setups, press t in the Metro terminal to start/stop live Atlas capture (opens /mockifyer-atlas-live).

Run the suite and publish Atlas docs for free

You do not need a paid CI plan for this. In a public repo, GitHub-hosted Linux runners and GitHub Pages are free. The WanderWeird demo in sgedda/mockifyer does both in one workflow: it runs the full Playwright E2E/integration suite (npx playwright test), uploads the auto-generated Atlas report from e2e/atlas-report/, and — on main, from the nightly schedule or a manual workflow_dispatch — publishes that report to GitHub Pages.

The E2E job uses ubuntu-24.04; the Pages deploy uses ubuntu-latest. Both are ordinary GitHub-hosted Linux runners. No self-hosted machines, no paid extras.

The live WanderWeird Atlas page — generated from that Playwright run — is at mockifyer.dev/atlas/wanderweird. The workflow itself is .github/workflows/e2e.yml.

What's next

The full walkthrough, FAQ, and edge cases live in the canonical guide: How to mock API calls in React Native.

Also useful: Getting Started, Stable React Native E2E, Handlers vs Recording, and the config reference. The repo is sgedda/mockifyer, with example apps react-native-expo-example and wanderweird-travel.

Top comments (0)