Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | 35x 1x 1443x 60x 60x 60x 111x 1500x 111x 111x 111x 111x 1119x 3x 3x 3x 111x 1119x 1119x 1119x 6495x 1299x 1299x 1299x 6495x 1299x 1059x 1059x 1059x 1059x 1119x 3x | import type { AxiosResponse } from "axios";
import { vi } from "vitest";
/**
* Drives every method on an API router and records the HTTP calls it makes.
*
* The routers are the frontend's half of the contract with svc-core, and the
* URL each one builds is assembled at runtime from a prefix, an `endpoint()`
* helper and a query-string builder. Reading the source cannot tell you what
* comes out of that; calling it can. So the contract test invokes each method
* for real against a stubbed transport and inspects the requests.
*/
export interface RecordedCall {
router: string;
method: string;
httpMethod: string;
/** Path only — host and query string stripped. */
path: string;
url: string;
}
export interface RecordingResult {
calls: RecordedCall[];
/** Methods that made no request under any argument shape. */
silent: string[];
}
/** A response shaped enough that `validRes()` accepts it and `.data` reads. */
const ok = (): AxiosResponse => ({
data: [],
status: 200,
statusText: "OK",
headers: {},
config: {} as AxiosResponse["config"],
});
/**
* Argument shapes to try, in order, until one gets through.
*
* A method's parameters are ids, bodies or option bags, and only ids reach
* the URL. Rather than hand-maintain a table of signatures that would rot,
* try the plausible shapes and keep the first that issues a request.
*/
const ARG_SHAPES: ((arity: number) => unknown[])[] = [
(n) => Array.from({ length: n }, () => "id"),
(n) => Array.from({ length: n }, (_, i) => (i === 0 ? "id" : {})),
(n) => Array.from({ length: n }, () => ({})),
(n) => Array.from({ length: n }, () => undefined),
];
/** Every callable property, whether an instance arrow-property or on the prototype. */
function methodNames(router: object): string[] {
const own = Object.keys(router).filter(
(k) => typeof (router as Record<string, unknown>)[k] === "function",
);
const proto = Object.getPrototypeOf(router) as object | null;
const inherited = proto
? Object.getOwnPropertyNames(proto).filter(
(k) =>
k !== "constructor" &&
typeof (router as Record<string, unknown>)[k] === "function",
)
: [];
// `endpoint` and `validRes` are URL plumbing, not endpoints of their own.
const PLUMBING = new Set(["endpoint", "validRes", "config"]);
return [...new Set([...own, ...inherited])].filter((k) => !PLUMBING.has(k));
}
export async function recordRouterCalls(
axiosMock: Record<string, ReturnType<typeof vi.fn>>,
routers: Record<string, object>,
host: string,
): Promise<RecordingResult> {
const calls: RecordedCall[] = [];
const silent: string[] = [];
for (const [routerName, router] of Object.entries(routers)) {
for (const name of methodNames(router)) {
const fn = (router as Record<string, (...a: unknown[]) => unknown>)[name];
let recorded = false;
for (const shape of ARG_SHAPES) {
for (const verb of Object.keys(axiosMock)) axiosMock[verb].mockClear();
try {
await fn(...shape(fn.length));
} catch {
// A method may reject on a placeholder argument (a body it reads
// fields off, say) *after* issuing its request. The request is what
// we are here for, so keep whatever was recorded.
}
const made = Object.entries(axiosMock).flatMap(([verb, spy]) =>
spy.mock.calls.map((args) => ({ verb, url: String(args[0]) })),
);
if (made.length > 0) {
for (const { verb, url } of made) {
calls.push({
router: routerName,
method: name,
httpMethod: verb.toUpperCase(),
path: url.replace(host, "").split("?")[0],
url,
});
}
recorded = true;
break;
}
}
if (!recorded) silent.push(`${routerName}.${name}`);
}
}
return { calls, silent };
}
export { ok as okResponse };
|