-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.ts
More file actions
80 lines (65 loc) · 3.11 KB
/
Copy pathsetup.ts
File metadata and controls
80 lines (65 loc) · 3.11 KB
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
import { expect } from "vitest";
interface CustomMatchers<R = unknown> {
toContainHeaders(expectedHeaders: Record<string, string>): R;
}
declare module "vitest" {
interface Assertion<T = any> extends CustomMatchers<T> {}
interface AsymmetricMatchersContaining extends CustomMatchers {}
}
expect.extend({
toContainHeaders(actual: unknown, expectedHeaders: Record<string, string>) {
const isHeaders = actual instanceof Headers;
const isPlainObject = typeof actual === "object" && actual !== null && !Array.isArray(actual);
if (!isHeaders && !isPlainObject) {
throw new TypeError("Received value must be an instance of Headers or a plain object!");
}
if (typeof expectedHeaders !== "object" || expectedHeaders === null || Array.isArray(expectedHeaders)) {
throw new TypeError("Expected headers must be a plain object!");
}
const missingHeaders: string[] = [];
const mismatchedHeaders: Array<{ key: string; expected: string; actual: string | null }> = [];
for (const [key, value] of Object.entries(expectedHeaders)) {
let actualValue: string | null = null;
if (isHeaders) {
// Headers.get() is already case-insensitive
actualValue = (actual as Headers).get(key);
} else {
// For plain objects, do case-insensitive lookup
const actualObj = actual as Record<string, string>;
const lowerKey = key.toLowerCase();
const foundKey = Object.keys(actualObj).find((k) => k.toLowerCase() === lowerKey);
actualValue = foundKey ? actualObj[foundKey] : null;
}
if (actualValue === null || actualValue === undefined) {
missingHeaders.push(key);
} else if (actualValue !== value) {
mismatchedHeaders.push({ key, expected: value, actual: actualValue });
}
}
const pass = missingHeaders.length === 0 && mismatchedHeaders.length === 0;
const actualType = isHeaders ? "Headers" : "object";
if (pass) {
return {
message: () => `expected ${actualType} not to contain ${this.utils.printExpected(expectedHeaders)}`,
pass: true,
};
} else {
const messages: string[] = [];
if (missingHeaders.length > 0) {
messages.push(`Missing headers: ${this.utils.printExpected(missingHeaders.join(", "))}`);
}
if (mismatchedHeaders.length > 0) {
const mismatches = mismatchedHeaders.map(
({ key, expected, actual }) =>
`${key}: expected ${this.utils.printExpected(expected)} but got ${this.utils.printReceived(actual)}`,
);
messages.push(mismatches.join("\n"));
}
return {
message: () =>
`expected ${actualType} to contain ${this.utils.printExpected(expectedHeaders)}\n\n${messages.join("\n")}`,
pass: false,
};
}
},
});