Testing
Utilities for testing code that uses createRestClient() or PipelineOrchestrator without hitting a real backend. Import from the separate rest-pipeline-js/testing entry point, so none of it ships in a production bundle.
createMockAdapter(routes)
ts
createMockAdapter(routes: MockRoute[]): MockAdapterReplaces the network with a set of route definitions — an HttpAdapter (see HTTP Adapter) backed by call history and (optionally) sequenced responses for exercising retry.
ts
import { createRestClient } from 'rest-pipeline-js'
import { createMockAdapter } from 'rest-pipeline-js/testing'
const adapter = createMockAdapter([
{ method: 'GET', url: '/users/1', respond: { data: { id: 1, name: 'Ada' } } },
// Dynamic response — reads the request to build the reply
{
method: 'POST',
url: '/orders',
respond: (info) => ({ data: { id: 42, ...(info.data as object) }, status: 201 }),
},
// Sequence of responses, one per matching call — exercise retry logic:
// first two attempts fail, third succeeds. Repeats the last entry once exhausted.
{
method: 'GET',
url: '/flaky',
respond: [{ error: true, status: 503 }, { error: true, status: 503 }, { data: { ok: true } }],
},
])
const client = createRestClient({ baseURL: 'https://api.example.com', adapter })
const user = await client.get('/users/1')
// adapter.calls — history of every request handled, in order; assert on it in your tests
expect(adapter.calls).toHaveLength(1)Parameters
routes: MockRoute[]
| Field | Description |
|---|---|
method | HTTP method to match. Omit to match any method. |
url | Matches by substring (string) or .test() (RegExp) against the relative URL (config.url, e.g. /users/1), not the full URL. |
respond | A response object, a function (info) => response reading the request to build the reply, or an array of responses consumed one per call (repeats the last once exhausted). |
delayMs | Simulates network latency with a real setTimeout (works fine under vi.useFakeTimers()/similar). |
Returns
MockAdapter — an HttpAdapter plus:
calls— history of every request handled, in order.reset()— clearscallsand rewinds any array-respondsequences back to their start, without touching the routes themselves.
Notes
- A response with
status >= 400rejects by default (matching what axios/fetch do), thrown asErrorwith.statusand.response.status/.response.data/.response.headersset — enough forretry.retriableStatus,circuitBreaker, and error interceptors to work against. Override with an expliciterror: true/falseon the response spec. - No route matching a request throws immediately with a clear message, instead of hanging — a test with a missing route setup fails loudly.
See examples/mock-adapter.ts for a fuller example, including use with PipelineOrchestrator via httpConfig.