Mock REST and GraphQL APIs in JavaScript: Tools, Fixtures, and Local Development Workflows
JavaScriptAPI MockingMock Service WorkerGraphQLTesting

Mock REST and GraphQL APIs in JavaScript: Tools, Fixtures, and Local Development Workflows

JJS Tools Editorial Team
2026-11-19
8 min read

A practical checklist for mocking REST and GraphQL APIs in JavaScript with fixtures, request interception, failure states, and contract checks.

Mocking an API lets you build and test a JavaScript interface before a backend is available. This guide compares practical REST and GraphQL mocking approaches, then gives reusable fixtures, failure scenarios, and a checklist for keeping local mocks useful instead of fragile.

Overview

An API mock is a controlled substitute for a real service. It can return predictable data, delay a response, simulate an error, or expose an incomplete result so that you can develop loading, empty, validation, and failure states deliberately.

The best choice depends on where the request originates and what you need to observe:

ApproachBest fitStrengthCheck before adopting
Request interception libraryBrowser development, tests, and StorybookExercises application code without requiring a separate mock serverBrowser, Node.js, test-runner, and framework adapters
Local mock serverTeams that need a shared HTTP endpointWorks with many clients and can be inspected independentlyStartup scripts, port management, state handling, and CI setup
In-process request stubsFocused unit testsFast and precise for a single moduleWhether the stub matches the real request shape and serialization
API client or design tool mocksExploring an endpoint contract or sharing examplesUseful for manual calls and early collaborationHow fixtures are exported, versioned, and used by automated tests

For frontend development, request interception is often a practical default because the application continues to use its normal fetch or HTTP client. A local server can be preferable when several applications, mobile clients, or manual tools need the same endpoint. In Node.js tests, use the test runner's supported interception or stubbing mechanism and keep the test focused on behavior rather than implementation details.

Mock Service Worker (MSW) is one commonly considered option for intercepting requests at the network boundary. Its browser and Node.js workflows are different, and its REST and GraphQL APIs may change across releases, so confirm the current setup and handler syntax in the project documentation before copying an example into production code.

Checklist by scenario

Browser development without a backend

  1. List the exact requests the screen makes: method, URL, query parameters, headers, and body.
  2. Create one handler for the normal response and separate handlers for loading, empty, validation, authorization, and server-error states.
  3. Start the mock layer from the same development command or document the required setup clearly.
  4. Keep the application code unchanged where possible. A component should call its normal API client, not a mock-only function.
  5. Use realistic identifiers, dates, pagination fields, and relationships so that UI assumptions become visible early.

A minimal REST fixture can be kept in a JavaScript module or JSON file:

export const userFixture = {
  id: "user-101",
  name: "Mina Patel",
  email: "mina@example.test",
  roles: ["editor"],
  createdAt: "2025-01-15T10:00:00.000Z"
};

export const listResponse = {
  items: [userFixture],
  page: 1,
  pageSize: 20,
  total: 1
};

The .test domain makes it clear that the address is not a real customer domain. Avoid placing real personal data, access tokens, or production exports in fixtures.

REST request interception

Define handlers around the contract your client consumes. The exact imports and APIs depend on the selected library version, but the shape of a handler is usually similar:

const getUsers = ({ request }) => {
  const url = new URL(request.url);
  const role = url.searchParams.get("role");

  const items = role
    ? listResponse.items.filter((user) => user.roles.includes(role))
    : listResponse.items;

  return Response.json({
    ...listResponse,
    items,
    total: items.length
  });
};

Use the current response helper for your chosen interception library rather than assuming that a browser Response object is accepted in every environment. The important design decision is to parse request inputs and return the same envelope your application expects.

Node.js tests

For a service or data-access test, intercept at the HTTP boundary when you want to verify serialization, status handling, and retry behavior. Stub a lower-level function only when the test is specifically about business logic and an HTTP call would add noise.

  • Reset handlers and mutable fixture state after each test.
  • Assert both the result and the request that produced it.
  • Include tests for non-2xx responses, malformed JSON, timeouts, and aborted requests where those cases affect application behavior.
  • Keep network access disabled or explicitly controlled in CI so a test cannot silently use a live service.

When a test fails, record the method, URL, query, request body, status, and response body in the failure output. This makes a stale mock easier to diagnose than a generic “request was not handled” message.

Storybook and component development

Component stories should demonstrate states rather than only the successful response. Create stories for:

  • initial loading;
  • one item and many items;
  • no results after filtering;
  • field-level validation errors;
  • an unauthorized response;
  • a slow response that exposes layout behavior; and
  • a server failure with a retry action.

Keep story-specific overrides close to the story, while shared entities and contract-shaped defaults belong in reusable fixtures. This prevents one visual test from changing every other screen.

GraphQL applications

GraphQL mocks must account for the operation name, query or document, variables, and the response's data and errors behavior. A useful fixture mirrors the selection set consumed by the component:

export const projectQueryResponse = {
  data: {
    project: {
      id: "project-7",
      name: "Documentation refresh",
      status: "ACTIVE",
      owner: { id: "user-101", name: "Mina Patel" }
    }
  }
};

Test variable-sensitive behavior. A search query with {"term":"api"} should not automatically return the same result as an empty search. Also test partial GraphQL results, where data contains usable fields but errors is present. Whether your client renders, retries, or rejects that response is client-specific and should be verified rather than assumed.

Latency and error simulation

Successful responses are not enough to validate an interface. Add controlled variations without making every test slow:

const delayedResponse = async () => {
  await new Promise((resolve) => setTimeout(resolve, 800));
  return Response.json(listResponse);
};

const errorResponse = () =>
  new Response(JSON.stringify({
    code: "UPSTREAM_UNAVAILABLE",
    message: "Please try again."
  }), {
    status: 503,
    headers: { "Content-Type": "application/json" }
  });

Prefer a deterministic delay or an explicit scenario switch over random failures. Randomness can make local development and CI results difficult to reproduce.

What to double-check

Contract alignment

Compare each fixture with the API contract, schema, OpenAPI document, GraphQL schema, or representative backend response. Check field names, casing, nullability, enum values, numeric types, date formats, pagination, and error envelopes. A mock that is convenient but structurally inaccurate can hide integration defects.

When an endpoint changes, update the contract and fixture together. If possible, add contract tests that compare the consumer's expectations with the provider's implementation. These tests should complement—not replace—UI and integration tests.

Request details

  • Does the handler match the correct HTTP method?
  • Does it include the API prefix and version used by the application?
  • Are query parameters encoded and compared consistently?
  • Does the mock inspect authentication without treating a fake token as valid security?
  • Does the request body distinguish omitted fields from fields explicitly set to null?

Mocks should help test authorization flows, but they must never be used to claim that a token is genuinely valid. For safe token handling and debugging boundaries, see the JavaScript JWT implementation guide.

Tool and package maintenance

Record the package versions, adapters, setup files, and startup commands used by the mock layer. When upgrading a mocking package, read its migration notes and run browser, Node.js, Storybook, and CI checks as applicable. The NPM dependency upgrade workflow provides a useful structure for planning and rolling back package changes.

Also confirm whether the mock library supports the project's module format, test runner, fetch implementation, GraphQL client, and runtime. A package can be appropriate in one environment and awkward in another.

Common mistakes

  • Mocking only the happy path. Add empty, slow, unauthorized, malformed, and server-error responses before declaring a screen complete.
  • Using production data as fixtures. Sanitize data and replace identifying values with stable, fictional records.
  • Duplicating business logic in the mock. A mock should represent a contract, not recreate the backend. Keep filtering and state transitions simple unless they are required to test the client.
  • Letting fixtures drift. Give fixture changes code review and link them to the endpoint or schema change that caused them.
  • Relying on global mutable state. Reset data between tests and avoid order-dependent scenarios.
  • Testing only mocked requests. Include a smaller number of integration or contract checks against the real provider or a controlled environment when feasible.
  • Hard-coding delays everywhere. Keep latency simulation opt-in so normal tests remain fast and deterministic.
  • Ignoring unhandled requests. Treat unexpected network calls as useful feedback during development and CI rather than silently returning a generic response.

If a mock-related change adds a large dependency or increases browser payloads, measure the effect and consider whether the mock should load only in development, tests, or Storybook. Dependency and bundle review practices can help here; see the JavaScript bundle analysis guide.

When to revisit

Review the mock workflow whenever a feature starts, an endpoint changes, a backend failure needs reproduction, or a teammate needs a reliable local setup. Also schedule a review before major planning or release cycles and at least twice a year if the mock layer is business-critical.

Use this short maintenance checklist:

  1. List all handlers and remove endpoints the application no longer calls.
  2. Compare fixtures with the current REST or GraphQL contract.
  3. Run normal, empty, loading, authorization, validation, and failure scenarios.
  4. Run the relevant browser, Node.js, Storybook, and CI workflows.
  5. Check package versions, adapters, setup files, and framework compatibility against current project requirements.
  6. Document how to add a fixture, override a response, and reproduce a known failure.

A good mock is not a second backend. It is a small, visible test surface that makes API assumptions explicit and gives developers dependable feedback. Start with one contract-shaped fixture and one failure variant, then expand the checklist as the application reveals new states.

Related Topics

#JavaScript#API Mocking#Mock Service Worker#GraphQL#Testing
J

JS Tools Editorial Team

Senior SEO Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.