Skip to main content
Version: v10.5.0

Mocking

Read the API Reference »

A mock replaces the adapter for one request instance. The request still goes through the dispatcher, the cache and every event, so loading states, progress, retries and cancelation behave as with a real server. Use mocks for tests, stories and building a UI before the API exists.

Purpose
  1. Return fake data or errors with full type safety.
  2. Simulate timing: request and response time, progress and timeouts.
  3. Keep the lifecycle: events, cache writes and aborts work as usual.
Live results

Return data or errors​

The mock callback receives { request, requestId } and returns a response with a status and data or error. It can be async. Return an error to simulate a failure.

const getUser = client.createRequest<{ response: User }>()({
endpoint: "/users/:userId",
});

getUser.setMock(({ request }) => {
if (request.params?.userId === 0) {
return { error: new Error("Not found"), status: 404 };
}
return {
data: { id: Number(request.params?.userId), name: "Ann" },
status: 200,
};
});

PartialBy<Omit<ResponseType<Response, Error, AdapterType>, (data | error | responseTimestamp | requestTimestamp)>, (extra | success)> & ({ data: Response; error?: Error } | { data?: Response; error: Error })


Simulate timing, progress and timeouts​

The second argument sets how the mock behaves over time. The request phase emits upload progress, the response phase download progress.

MockerConfigType
Name Type Description
requestTime
number
Simulates how long the request to the server should take (in milliseconds)
responseTime
number
Indicates how long the response from the server should take (in milliseconds). If their combined total takes longer than provided timeout, each value will be automatically adjusted to last half of the timeout time
timeout
number
Informs how long the request should take before returning a timeout error (in milliseconds)
totalDownloaded
number
total number of 'bytes' to be downloaded.
totalUploaded
number
total number of 'bytes' to be uploaded.

Timeout

Aborting works as with a real request: send() resolves with an abort error.

Abort

Mock setters change the instance​

setMock, clearMock and setMockingEnabled change the request they are called on, unlike the other setters, which return a clone. Clones made later copy the mock, clones made earlier do not. Set the mock on the base request first.

// made before the mock: not mocked
const getFirstUser = getUser.setParams({ userId: 1 });

getUser.setMock(() => ({ data: { id: 2, name: "Mocked" }, status: 200 }));

getUser.setParams({ userId: 2 }); // made after the mock: mocked

Every SDK property access creates a new request, so keep a reference: const getUsers = sdk.users.$get.


Mock a whole SDK​

$configure with function values attaches mocks to SDK endpoints. It returns a new SDK, so the original stays unmocked.

test/sdk.ts
import type { RequestInstance } from "@hyper-fetch/core";
import { sdk } from "../src/api/sdk";

export const testSdk = sdk.$configure({
"users.$get": (request: RequestInstance) =>
request.setMock(() => ({ data: [{ id: 1, name: "John" }], status: 200 })),
"posts.$get": (request: RequestInstance) =>
request.setMock(() => ({ data: [], status: 200 })),
});

See SDK configuration.


Turn mocks off​

CallEffect
request.clearMock()Removes the mock from the request
request.setMockingEnabled(false)Keeps the mock but sends real requests until turned back on
client.setEnableGlobalMocking(false)Ignores the mocks of every request of the client

Summary
  • setMock(callback, config) replaces the adapter for one request and keeps the whole lifecycle.
  • Return data or error with a status. Set timing, progress and timeout in the config.
  • Mock setters change the instance. Set them before deriving clones, and keep SDK requests in a variable.

Next steps​

Runnable examples: Mocking and Testing.

Mocking in tests
Mock requests and SDKs in your test suite.
Request API reference
setMock, clearMock and setMockingEnabled signatures.