-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvitest.extend.ts
More file actions
39 lines (34 loc) · 1.19 KB
/
Copy pathvitest.extend.ts
File metadata and controls
39 lines (34 loc) · 1.19 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
import { expect } from "vitest";
expect.extend({
toThrowErrorMatching<C extends ErrorConstructor>(f: unknown, ctor: C, expected: string | RegExp) {
if (typeof f !== "function")
throw new Error("Must expect a function to call");
const { isNot } = this;
let behavior: string;
let threw: Error | null = null;
try {
(f as () => void)();
behavior = "didn't throw";
} catch (e) {
if (e instanceof ctor && e.name === ctor.name) {
threw = e;
behavior = `threw ${e.name}, message ${e.message}`;
} else {
behavior = `threw not a ${ctor.name}`;
}
}
let pass = false;
if (threw !== null) {
const actualMessage = threw.message;
pass = typeof expected === "string"
? actualMessage.includes(expected)
: expected.test(actualMessage);
}
return {
pass,
message: pass
? () => `expected ${f as any} to ${isNot ? "not throw" : "throw"} a ${ctor.name} with message matching ${expected.toString()}`
: () => `expected ${f as any} to ${isNot ? "not throw" : "throw"} a ${ctor.name} with message matching ${expected.toString()} (actual behavior: ${behavior})`,
};
},
});