Skip to content

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[]): MockAdapter

Replaces 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[]

FieldDescription
methodHTTP method to match. Omit to match any method.
urlMatches by substring (string) or .test() (RegExp) against the relative URL (config.url, e.g. /users/1), not the full URL.
respondA 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).
delayMsSimulates 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() — clears calls and rewinds any array-respond sequences back to their start, without touching the routes themselves.

Notes

  • A response with status >= 400 rejects by default (matching what axios/fetch do), thrown as Error with .status and .response.status/.response.data/.response.headers set — enough for retry.retriableStatus, circuitBreaker, and error interceptors to work against. Override with an explicit error: true/false on 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.