Code Reference

API Fetch Mock

Jest · Example / how-to

Jest · Example / how-to


📋 Overview

Unit-test a small API client by mocking fetch for success and error paths.

🔧 Core concepts

PathExpect
200 JSONParsed object
404Thrown / mapped error
Network failRejects

💡 Examples

// api.js
export async function getItem(id) {
  const res = await fetch(`/api/items/${id}`);
  if (!res.ok) {
    const err = new Error('request failed');
    err.status = res.status;
    throw err;
  }
  return res.json();
}

// api.test.js
import { getItem } from './api';

afterEach(() => jest.restoreAllMocks());

test('getItem success', async () => {
  global.fetch = jest.fn().mockResolvedValue({
    ok: true,
    json: async () => ({ id: '1', title: 'Hi' }),
  });
  await expect(getItem('1')).resolves.toEqual({ id: '1', title: 'Hi' });
});

test('getItem 404', async () => {
  global.fetch = jest.fn().mockResolvedValue({
    ok: false,
    status: 404,
    json: async () => ({}),
  });
  await expect(getItem('missing')).rejects.toMatchObject({ status: 404 });
});

⚠️ Pitfalls

  • Mock implementation must include json as a function.
  • Prefer MSW when many endpoints share cookies/headers.

On this page