Skip to main content

Mocking

A todo screen built before its API is ready. A mock answers the real request, and one switch sends it to the real DummyJSON endpoint instead.

beginnermockinguseFetcherrors
import { useFetch } from "@hyper-fetch/react";
import { useState } from "react";

import { applyMock, getTodos, type MockSettings, type Scenario, setMocking } from "./api";

const scenarios: Scenario[] = ["success", "empty", "error", "timeout"];
const initialSettings: MockSettings = { scenario: "success", latency: 800 };

// Mocks are set before the first render, so the first request is already mocked.
applyMock(initialSettings);

export const App = () => {
const [mocked, setMocked] = useState(true);
const [settings, setSettings] = useState(initialSettings);
const [progress, setProgress] = useState(0);

const updateMocked = (enabled: boolean) => {
setMocking(enabled);
setMocked(enabled);
};

const updateSettings = (next: MockSettings) => {
applyMock(next);
setSettings(next);
};

// `dependencies` sends the request again whenever the mock setup changes.
const {
data,
error,
loading,
status,
requestTimestamp,
responseTimestamp,
refetch,
onRequestStart,
onDownloadProgress,
} = useFetch(getTodos.setQueryParams({ limit: 5 }), { dependencies: [mocked, settings] });

// Mocked requests emit progress events too, so loaders and progress bars can be built before the API exists.
onRequestStart(() => setProgress(0));
onDownloadProgress(({ progress: value }) => setProgress(value));

const time = requestTimestamp && responseTimestamp ? responseTimestamp.getTime() - requestTimestamp.getTime() : null;

return (
<main className="container">
<hgroup>
<h1>Todos</h1>
<p>A screen built before its backend: switch between the mock and the real API.</p>
</hgroup>
<div className="grid-2">
<article>
<label>
<input
type="checkbox"
role="switch"
checked={mocked}
onChange={(event) => updateMocked(event.target.checked)}
/>
Use mocks
</label>
<fieldset disabled={!mocked}>
<legend>Mocked response</legend>
{scenarios.map((scenario) => (
<label key={scenario}>
<input
type="radio"
name="scenario"
checked={settings.scenario === scenario}
onChange={() => updateSettings({ ...settings, scenario })}
/>
{scenario}
</label>
))}
<label>
Latency: {settings.latency} ms
<input
type="range"
min={0}
max={3000}
step={100}
value={settings.latency}
disabled={settings.scenario === "timeout"}
onChange={(event) => updateSettings({ ...settings, latency: Number(event.target.value) })}
/>
</label>
</fieldset>
</article>

<article>
<header className="toolbar muted">
<span>
{mocked ? "Mock" : "dummyjson.com"} · status {status ?? "-"}
{time !== null && ` · ${time} ms`}
</span>
<button type="button" className="outline secondary" onClick={refetch} disabled={loading}>
Reload
</button>
</header>
{loading && <progress value={progress} max={100} />}
{error && <p className="error">Could not load todos: {error.message}</p>}
{!loading && !error && data?.todos.length === 0 && <p className="muted">Nothing to do.</p>}
<ul>
{!error &&
data?.todos.map((todo) => <li key={todo.id}>{todo.completed ? <del>{todo.todo}</del> : todo.todo}</li>)}
</ul>
</article>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/mocking hyper-fetch-react-mocking && cd hyper-fetch-react-mocking && npm install && npm run dev
What it shows
  1. setMock answers a request with data you return, without a server and without changing the component.
  2. Mock config sets the latency with requestTime and responseTime, and a timeout that fails the request.
  3. Error scenarios return an error and a status, so the error state is built before the API can fail.
  4. client.setEnableGlobalMocking(false) turns every mock off and sends the same request to the real API.

How it works​

  1. api.ts defines getTodos against the real /todos endpoint, with its final response type. The component only knows this request.

  2. applyMock() calls getTodos.setMock(callback, config). The callback reads the request (here the limit query param) and returns data, or error with a status:

    if (scenario === "error") return { error: new Error("Internal server error"), status: 500 };
    return { data: { todos: fixtures.slice(0, limit), total: fixtures.length }, status: 200 };
  3. setMock is the one setter that changes the request in place instead of returning a clone, so every clone created later, like getTodos.setQueryParams({ limit: 5 }) in App.tsx, carries the mock.

  4. The mock runs the full request lifecycle. useFetch gets loading, status and timestamps, and onDownloadProgress fills the progress bar from the simulated transfer.

  5. useFetch lists the mock settings in dependencies, so every change sends the request again.

  6. Use mocks calls client.setEnableGlobalMocking(). With mocks off, the request goes to DummyJSON and the UI stays the same, which is the point: nothing changes when the backend ships.

When to use it
  • Frontend work that starts before the API is ready.
  • Building loading, empty, error and timeout states on purpose instead of waiting for them to happen.
  • Demos and tests that should not depend on a live server.

Summary

setMock replaces the adapter for one request and keeps the rest of the lifecycle, so the UI is built and tested against loading, errors and timeouts before the backend exists. setEnableGlobalMocking(false) switches to the real API.