-
Notifications
You must be signed in to change notification settings - Fork 382
/
to-throw-error-with-type.ts
58 lines (51 loc) · 1.59 KB
/
to-throw-error-with-type.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
53
54
55
56
57
58
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import diff from 'jest-diff';
import MatcherUtils = jest.MatcherUtils;
export function toThrowErrorWithType(
this: MatcherUtils,
received: any,
ctor: any,
message?: string
) {
let error: Error | undefined;
try {
received();
} catch (err: any) {
error = err;
}
if (error === undefined) {
return {
message: () => 'Received function did not throw',
pass: false,
};
}
if (error === null || typeof error !== 'object' || error.constructor !== ctor) {
return {
message: () =>
`Expected function to throw an instance of\n\n` +
`Expected ${this.utils.printExpected(ctor.name)}\n` +
`Received ${this.utils.printReceived(error!.constructor.name)}`,
pass: false,
};
}
if (error.message !== message) {
const errorDiff = diff.diffStringsUnified(message!, error.message);
return {
message: () =>
`Expected function to throw an error with message\n\n` +
`Difference ${errorDiff}\n` +
`Expected ${this.utils.printExpected(message)}\n` +
`Received ${this.utils.printReceived(error!.message)}`,
pass: false,
};
}
return {
message: () => `Expected function not to throw an error`,
pass: true,
};
}