Mocking
Mocking lets you work without calling the live service during development or tests.
You just need to set a mocking config on your endpoint:
/endpoint.ts
import { RequestMethod } from "api-def";
export const fetchHealthCheck = api
.endpoint()
.responseOf<{ success: boolean }>()
.build({
id: "fetch_health_check",
name: "Health Check",
description: "Returns success as true",
path: "/status/health-check",
method: RequestMethod.GET,
mocking: {
delay: [200, 2000],
handler: (context, res) => {
return res.status(200).send({
success: true,
});
},
},
});
Mock handlers receive a context object. Use context.request for the standard WHATWG Request:
mocking: {
handler: async (context, res) => {
const body = await context.request.json();
return res.status(200).send({
id: new URL(context.request.url).searchParams.get("id"),
body,
});
},
}
The convenience properties on the mock context, such as context.body, context.query, context.headers, context.url, and context.state, are also supported. They are exposed as getters, so the API can evolve without changing the handler shape.
Mock handlers can also return a standard Response directly:
mocking: {
handler: () => {
return Response.json({ success: true }, { status: 200 });
},
}
Mocks are then enabled/disabled for all endpoints at the API level:
/api.ts
import { Api } from "api-def";
const API = new Api({
name: "My Backend",
baseUrl: "http://localhost:5000/v1",
mocking: { enabled: true },
});
export default API;
Calling an endpoint with no mocking configuration when mocking is enabled at the API level will result in an exception being thrown.