Verifying requests
| Method | Returns |
|---|---|
countRequests(criteria) | How many requests matched since the last reset |
findRequests(criteria) | The matching requests, oldest first – RecordedRequest[] |
Both query WireMock's request journal – why that matters. client in the examples
is a fetch-based payments client.
Count requests
it("countRequests(): how many requests matched since the last reset", async () => {
await client.list();
await client.list(2);
expect(await wiremock.countRequests({ method: "GET", url: "/payments" })).toBe(1); // exact path and query
expect(await wiremock.countRequests({ method: "GET", urlPath: "/payments" })).toBe(2); // any query
expect(await wiremock.countRequests({ method: "DELETE", urlPathPattern: "/payments/.*" })).toBe(0);
});
Source: examples/verification/verification.e2e.test.ts (lines 33–40)
url matches path and query exactly; urlPath the path with any query. Unmatched requests are
recorded too.
Inspect requests
it("findRequests(): the recorded requests, for assertions on bodies and headers", async () => {
const payment: NewPayment = { amount: "9.99", currency: "USD" };
await client.create(payment, randomUUID());
const [request] = await wiremock.findRequests(CREATE_PAYMENT);
expect(jsonBody(request)).toEqual(payment);
expect(request.headers).toMatchObject({ Authorization: "Bearer test-key" });
});
Source: examples/verification/verification.e2e.test.ts (lines 44–52)
Match on query, headers and body
WiremockRequestCriteria is a stub's request pattern. Name the ones you reuse:
/** Criteria are plain data: name them once, reuse them in every assertion. */
export const LIST_PAYMENTS = { method: "GET", urlPath: "/payments" } satisfies WiremockRequestCriteria;
export const CREATE_PAYMENT = {
method: "POST",
url: "/payments",
headers: {
"Content-Type": { equalTo: "application/json" },
"Idempotency-Key": { matches: "[0-9a-f-]{36}" },
},
} satisfies WiremockRequestCriteria;
Source: examples/verification/verification.ts (lines 14–24)
it("criteria use WireMock's request matching: query, header and body matchers", async () => {
await client.list(2);
await client.create({ amount: "120.00", currency: "EUR" }, randomUUID());
expect(await wiremock.countRequests({ method: "GET", urlPath: "/payments", queryParameters: { page: { equalTo: "2" } } })).toBe(1);
expect(await wiremock.countRequests({ method: "ANY", urlPattern: "/payments.*", headers: { Authorization: { matches: "Bearer .+" } } })).toBe(2);
expect(
await wiremock.countRequests({
method: "POST",
urlPath: "/payments",
bodyPatterns: [{ matchesJsonPath: "$[?(@.currency == 'EUR')]" }, { equalToJson: { amount: "120.00" }, ignoreExtraElements: true }],
}),
).toBe(1);
});
Source: examples/verification/verification.e2e.test.ts (lines 56–69)
| Field | Matches |
|---|---|
method | "GET", "POST", … – "ANY" for all |
url / urlPath | Path and query / path only – exactly |
urlPattern / urlPathPattern | The same, by regular expression |
headers, queryParameters | Name → matcher: { equalTo }, { matches }, { absent: true }, … |
bodyPatterns | equalToJson, matchesJsonPath, contains, … |
Other WireMock fields pass through. Matcher values are strings: { equalTo: 2 } is
rejected.
Read a recorded request
it("a RecordedRequest carries the URL, method, headers, query and body", async () => {
await client.list(3);
const [request] = await wiremock.findRequests(LIST_PAYMENTS);
expect(request).toMatchObject({
url: "/payments?page=3", // path and query
absoluteUrl: wiremock.getUrl("/payments?page=3"),
method: "GET",
queryParams: { page: { key: "page", values: ["3"] } },
body: "", // WireMock records "" for requests without a body
});
expect(request.headers?.Accept).toBe("application/json");
expect(request.loggedDate).toBeLessThanOrEqual(Date.now()); // epoch milliseconds
});
Source: examples/verification/verification.e2e.test.ts (lines 73–87)
RecordedRequest field | Content |
|---|---|
url, absoluteUrl | Path and query; with scheme, host and port |
method | The HTTP method |
headers | Name → value |
queryParams | Name → { key, values } |
body | Text – "" without a body |
loggedDate | Epoch milliseconds |
JSON bodies:
/** The parsed JSON body of a recorded request – WireMock records `""` for requests without one. */
export function jsonBody<T = unknown>(request: RecordedRequest): T {
if (!request.body) throw new Error(`${request.method} ${request.url} has no body`);
return JSON.parse(request.body) as T;
}
Source: examples/verification/verification.ts (lines 28–32)
Write a reusable assertion
Fails with the journal in the message:
/** The journal methods an assertion needs – a fake suffices in unit tests. */
export type RequestJournal = Pick<StartedWiremockContainer, "countRequests" | "findRequests">;
/** Asserts that exactly `times` requests matched; lists every received request otherwise. */
export async function expectRequested(journal: RequestJournal, criteria: WiremockRequestCriteria, times = 1): Promise<void> {
const count = await journal.countRequests(criteria);
if (count === times) return;
const received = await journal.findRequests({ method: "ANY", urlPattern: ".*" });
const list = received.map(({ method, url }) => `${method} ${url}`).join(", ") || "none";
throw new Error(`expected ${times} request(s) matching ${JSON.stringify(criteria)}, got ${count}; received: ${list}`);
}
Source: examples/verification/verification.ts (lines 36–46)
it("expectRequested(): one reusable assertion, with the journal in its message", async () => {
await client.create({ amount: "1.00", currency: "USD" }, randomUUID());
await expectRequested(wiremock, CREATE_PAYMENT);
await expectRequested(wiremock, LIST_PAYMENTS, 0);
});
Source: examples/verification/verification.e2e.test.ts (lines 91–96)
Unit-test it with a fake journal:
/** A journal holding `requests`, counting those with the criteria's method. */
const fakeJournal = (requests: RecordedRequest[]): RequestJournal => ({
countRequests: async ({ method }) => requests.filter((request) => request.method === method).length,
findRequests: async () => requests,
});
Source: examples/verification/verification.test.ts (lines 13–17)
Background
The code under test
The examples test this client, given the container's URL:
export class PaymentsClient {
readonly #baseUrl: string;
readonly #headers: Readonly<Record<string, string>>;
/** @param baseUrl E.g. `wiremock.getUrl()` in tests, the real API's URL in production. */
constructor(baseUrl: string, options: PaymentsClientOptions = {}) {
this.#baseUrl = baseUrl.replace(/\/+$/u, "");
this.#headers = {
Accept: "application/json",
...(options.apiKey === undefined ? {} : { Authorization: `Bearer ${options.apiKey}` }),
};
}
/** `GET /payments`, or `GET /payments?page=<page>`. */
async list(page?: number): Promise<PaymentPage> {
return this.#request("GET", page === undefined ? "/payments" : `/payments?page=${page}`);
}
/** `GET /payments/<id>`. */
async get(id: string): Promise<Payment> {
return this.#request("GET", `/payments/${encodeURIComponent(id)}`);
}
/** `POST /payments` with a JSON body and an idempotency key. */
async create(payment: NewPayment, idempotencyKey: string): Promise<PaymentReceipt> {
return this.#request("POST", "/payments", payment, { "Idempotency-Key": idempotencyKey });
}
async #request<T>(method: string, path: string, body?: object, headers: Record<string, string> = {}): Promise<T> {
const response = await fetch(`${this.#baseUrl}${path}`, {
method,
headers: { ...this.#headers, ...headers, ...(body ? { "Content-Type": "application/json" } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
if (!response.ok) {
throw new PaymentsApiError(response.status, `${method} ${path} failed with ${response.status}: ${await response.text()}`);
}
return (await response.json()) as T;
}
}
Source: examples/app/payments-client.ts (lines 53–92)
Unit tests and WireMock tests
A unit test with a stubbed fetch checks what your code passes to fetch:
/**
* Unit tests of the system under test, with `fetch` stubbed – fast, but they only prove what the
* client *sends*. `verification/verification.e2e.test.ts` proves it against a real HTTP server.
*
* @see https://hella-web3.github.io/wiremock-testcontainers-nodejs/docs/guides/verifying-requests
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import { PaymentsApiError, PaymentsClient } from "./payments-client";
const BASE_URL = "http://localhost:8080";
/** Stubs `fetch` with `response` and returns the mock, to inspect the request. */
const stubFetch = (response: Response) => {
const mock = vi.fn<typeof fetch>(async () => response);
vi.stubGlobal("fetch", mock);
return mock;
};
afterEach(() => {
vi.unstubAllGlobals();
});
describe("PaymentsClient", () => {
it("lists payments", async () => {
const page = { items: [], meta: { totalItems: 0 } };
const mock = stubFetch(Response.json(page));
await expect(new PaymentsClient(BASE_URL).list()).resolves.toEqual(page);
expect(mock).toHaveBeenCalledWith(`${BASE_URL}/payments`, expect.objectContaining({ method: "GET" }));
});
it("lists a given page, ignoring a trailing slash of the base URL", async () => {
const mock = stubFetch(Response.json({ items: [], meta: { totalItems: 0 } }));
await new PaymentsClient(`${BASE_URL}/`).list(2);
expect(mock).toHaveBeenCalledWith(`${BASE_URL}/payments?page=2`, expect.objectContaining({ method: "GET" }));
});
it("gets one payment by its URL-encoded id", async () => {
const payment = { id: "pay 1", amount: "1.00", currency: "EUR", status: "SETTLED" };
const mock = stubFetch(Response.json(payment));
await expect(new PaymentsClient(BASE_URL).get("pay 1")).resolves.toEqual(payment);
expect(mock).toHaveBeenCalledWith(`${BASE_URL}/payments/pay%201`, expect.anything());
});
it("creates a payment: JSON body, idempotency key and API key", async () => {
const mock = stubFetch(Response.json({ id: "p-1", status: "PENDING" }, { status: 201 }));
const client = new PaymentsClient(BASE_URL, { apiKey: "secret" });
await expect(client.create({ amount: "9.99", currency: "USD" }, "key-1")).resolves.toEqual({ id: "p-1", status: "PENDING" });
expect(mock).toHaveBeenCalledWith(`${BASE_URL}/payments`, {
method: "POST",
headers: {
Accept: "application/json",
Authorization: "Bearer secret",
"Idempotency-Key": "key-1",
"Content-Type": "application/json",
},
body: '{"amount":"9.99","currency":"USD"}',
});
});
it("throws a PaymentsApiError with the status for non-2xx answers", async () => {
stubFetch(new Response("no such payment", { status: 404 }));
const error = await new PaymentsClient(BASE_URL).get("missing").catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(PaymentsApiError);
expect(error).toMatchObject({ name: "PaymentsApiError", status: 404, message: "GET /payments/missing failed with 404: no such payment" });
});
});
Source: examples/app/payments-client.test.ts
The journal records what reached a real server – URL encoding, headers, serialised bodies – and your code's real HTTP stack runs, including its handling of real status codes. Use unit tests for logic, WireMock for the HTTP boundary.