-
Notifications
You must be signed in to change notification settings - Fork 4
/
_assertions.ts
52 lines (48 loc) · 1.33 KB
/
_assertions.ts
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
import { AssertionError, stripColor } from "./dev_deps.ts";
interface Constructor {
// deno-lint-ignore no-explicit-any
new (...args: any[]): any;
}
export function assertInstanceOf<T = unknown>(
instance: T,
expectedClass: Constructor,
msg?: string,
): T {
if (instance instanceof expectedClass) {
return instance;
}
throw new AssertionError(
`Expected instance to be instance of "${expectedClass.name}", but was "${(typeof instance ===
"function"
? instance.constructor.name
: typeof instance)}"${msg ? `: ${msg}` : "."}`,
);
}
export function assertExpectError<T = unknown>(
error: T,
expectedErrorClass?: Constructor,
msgIncludes = "",
msg?: string,
): T {
if (!(error instanceof Error)) {
throw new AssertionError("A non-Error object was thrown.");
}
if (expectedErrorClass && !(error instanceof expectedErrorClass)) {
throw new AssertionError(
`Expected error to be instance of "${expectedErrorClass.name}", but was "${error.constructor.name}"${
msg ? `: ${msg}` : "."
}`,
);
}
if (
msgIncludes &&
!stripColor(error.message).includes(stripColor(msgIncludes))
) {
throw new AssertionError(
`Expected error message to include "${msgIncludes}", but got "${error.message}"${
msg ? `: ${msg}` : "."
}`,
);
}
return error;
}