Skip to content

Mock Server

In one line

A mock server fakes an API backend — returns predefined responses, lets you test frontend/integration without the real server.

In simple words

A mock server is a fake server that mimics a real API. It returns predefined responses to requests, allowing you to test without the actual backend service running.

Why use a mock server:

  1. Backend not ready — frontend can develop against the mock API
  2. Testing edge cases — simulate errors, timeouts, slow responses
  3. No external dependencies — tests don't need network or real services
  4. Deterministic — same responses every time, no flaky tests
  5. Fast — no real database queries or computation

What a mock server can do:

  • Return fixed responses for specific endpoints
  • Simulate different response statuses (200, 404, 500)
  • Add delays to simulate slow networks
  • Validate request format (contract testing)
  • Record requests for verification
  • Dynamically generate responses based on request

Tools: MSW (Mock Service Worker), WireMock, nock (Node.js), Prism, Postman Mock Server.

Example

javascript
// MSW (Mock Service Worker) — intercepts network requests
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';

const server = setupServer(
  // Normal response
  http.get('/api/users/1', () => {
    return HttpResponse.json({ id: 1, name: 'Ada' });
  }),

  // Simulate error
  http.get('/api/users/999', () => {
    return new HttpResponse(null, { status: 404 });
  }),

  // Simulate slow response
  http.get('/api/slow', async () => {
    await delay(5000); // 5 second delay
    return HttpResponse.json({ data: 'finally' });
  }),

  // Dynamic response based on request
  http.post('/api/users', async ({ request }) => {
    const body = await request.json();
    return HttpResponse.json({ id: Date.now(), ...body }, { status: 201 });
  })
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

MSW intercepts network requests and returns mock responses. You can simulate normal responses, errors, delays, and dynamic behavior — all without a real backend.

Common confusions

  • Confused with: mock objects

    The difference: A mock server simulates an entire HTTP API server — it intercepts network requests and returns responses. A mock object replaces a specific dependency (class/function) in unit tests — it's at the code level, not the network level. Mock servers are for integration/E2E tests; mock objects are for unit tests.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary