Skip to content

Instantly share code, notes, and snippets.

@reyronald
Last active August 24, 2023 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reyronald/8636a192725576746fc94f20239bb086 to your computer and use it in GitHub Desktop.
Save reyronald/8636a192725576746fc94f20239bb086 to your computer and use it in GitHub Desktop.
getNockPayloadCapturer.ts
const mockServer = nock("http://localhost", { allowUnmocked: false });
mockServer.put(`/api/clients/${client.id}/bills/bulk`).reply(200, bills);
const getCapturedPayload = getNockPayloadCapturer(mockServer);
await userEvent.click(screen.getByRole("button", { name: "Save" }));
const capturedPayload = await waitFor(getCapturedPayload);
expect(capturedPayload).toMatchInlineSnapshot()
import type nock from "nock/types";
export function getNockPayloadCapturer(scope: nock.Scope) {
const capturedPayloads: [string, unknown][] = [];
const activeMocks = scope.activeMocks();
const listener = (_req: unknown, _interceptorOptions: unknown, body: string) => {
const capturedPayload = JSON.parse(body);
capturedPayloads.push([activeMocks[capturedPayloads.length], capturedPayload]);
};
scope.on("request", listener);
const getCapturedPayloads = () => {
if (!scope.isDone() || capturedPayloads.length < activeMocks.length) {
throw new Error("Not done capturing yet.");
}
scope.removeListener("request", listener);
return capturedPayloads;
};
return getCapturedPayloads;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment