MockAPIProviderclass
new MockAPIProvider<P, R>(handler: RequestHandler = _mockHandler, source: APIProvider<P, R> = new ClientAPIProvider({ url: "https://api.mock.com" }))| Param | Type | |
|---|---|---|
handler | RequestHandler | The handler that produces a response for each request (defaults to echoing the request). Defaults to _mockHandler |
source | APIProvider<P, R> | The source provider used to build requests and parse responses. Defaults to new ClientAPIProvider({ url: "https://api.mock.com" }) |
| Return | |
|---|---|
MockAPIProvider<P, R> | Provider that records API calls and serves them from a handler without sending network requests. |
| Property | Type | |
|---|---|---|
.requestCalls | MockAPIRequestCall[] | Records of every request built by this provider. Defaults to [] readonly |
.fetchCalls | MockAPIFetchCall[] | Records of every fetch handled by this provider. Defaults to [] readonly |
.responseCalls | MockAPIResponseCall[] | Records of every response parsed by this provider. Defaults to [] readonly |
.handler | RequestHandler | The request handler that serves fetches in place of the network. required readonly |
Provider that records API calls and serves them from a handler without sending network requests.
- Extends
ThroughAPIProviderto delegate request building and response parsing to a sourceAPIProvider. - The source provider's
fetch()is never called — this provider intercepts all fetches and routes them through aRequestHandler. - Records
requestCalls,fetchCalls, andresponseCallsso tests can assert on what happened.
A wrapping provider for tests. MockAPIProvider intercepts fetches through a RequestHandler instead of hitting the network, and records every call it makes so a test can assert on them.
The constructor takes an optional RequestHandler and an optional source provider — both have defaults, so new MockAPIProvider() is enough for a provider that records calls and returns canned responses.
Usage
import { MockAPIProvider } from "shelving/api"
const api = new MockAPIProvider((request) => new Response(JSON.stringify({ id: "u_1", name: "Alice" })))
const user = await api.call(getUser, { id: "u_1" })
console.log(api.requestCalls) // inspect every recorded requestFor tests that exercise client and server logic together, use MockEndpointAPIProvider, which routes the mock transport through a real handler array.
Examples
const api = new MockAPIProvider(); const result = await api.call(endpoint, payload); expect(api.fetchCalls).toHaveLength(1);