← Back to archive

Repo of the Day

grug/data-mocks

Published: Feb 10, 2023

Open repository ↗

Library to mock local data requests using Fetch or XHR

Summary

data-mocks is a TypeScript library for intercepting REST and GraphQL requests during local development and returning mocked responses instead of hitting real backends. It works with the browser's fetch API and any XHR-based client such as axios, patching the underlying transports rather than the application code. The library supports multiple named scenarios that can be switched at runtime via a URL query string, which makes it practical for showing different states without a server.

What it is useful for

This library is useful when the backend an engineer depends on does not exist yet, is unreliable, or returns data that does not match the shape the UI needs. The README frames it as an alternative to running a separate local mock service or seeding a development database, both of which can drift out of sync with the real schema. It is also useful for QA and design reviews: a reviewer can append ?scenario=failedLogin to the URL and see a different set of mocked responses, including 4xx codes, custom headers, and artificial delays, without code changes.

How engineers can use it

Installation is npm install data-mocks (or yarn add data-mocks). Engineers define a Scenarios object whose keys are scenario names and whose values are arrays of mocks, then call injectMocks(scenarios, scenarioName). Each HttpMock is matched by a regex on the URL and an HTTP method (GET, POST, PUT, PATCH, DELETE), and returns a response, optional responseCode (defaults to 200), responseHeaders, and delay in milliseconds. The README shows a failedLogin scenario layered on top of default, where a 401 is returned for /login/ while other endpoints keep their default behavior.

For GraphQL, the method is set to 'GRAPHQL' and the mock contains an operations array; each operation must be either a query or mutation and must declare an operationName. The helper extractScenarioFromLocation(window.location) reads the ?scenario=... query string so the active scenario can be controlled by URL.

Integration snippets are provided for React, Angular, and vanilla JS. In all three, the README recommends dynamically importing data-mocks and the mock definitions only when process.env.NODE_ENV === 'development' (or environment.production is false in Angular) so the production bundle is not affected. The optional MockConfig object exposes allowXHRPassthrough and allowFetchPassthrough to let unmatched requests hit the real network, and disableConsoleWarningsForFetch to silence fetch-mock warnings. A documented gotcha is that every GraphQL operation must have an operation name; the mock will not match unnamed queries.