Mocking
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.
- Return fake data or errors with full type safety.
- Simulate timing: request and response time, progress and timeouts.
- Keep the lifecycle: events, cache writes and aborts work as usual.
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.
| Name | Type | Description |
|---|---|---|
| requestTime | | Simulates how long the request to the server should take (in milliseconds) |
| responseTime | | 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 | | Informs how long the request should take before returning a timeout error (in milliseconds) |
| totalDownloaded | | total number of 'bytes' to be downloaded. |
| totalUploaded | | total number of 'bytes' to be uploaded. |
Aborting works as with a real request: send() resolves with an abort error.
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.
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
| Call | Effect |
|---|---|
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 |
setMock(callback, config)replaces the adapter for one request and keeps the whole lifecycle.- Return
dataorerrorwith astatus. Set timing, progress andtimeoutin 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.