UNPKG

2.86 kBJavaScriptView Raw
1import { Predicate } from './predicate.js';
2export class ErrorPredicate extends Predicate {
3 /**
4 @hidden
5 */
6 constructor(options) {
7 super('error', options);
8 }
9 /**
10 Test an error to have a specific name.
11
12 @param expected - Expected name of the Error.
13 */
14 name(expected) {
15 return this.addValidator({
16 message: (error, label) => `Expected ${label} to have name \`${expected}\`, got \`${error.name}\``,
17 validator: error => error.name === expected,
18 });
19 }
20 /**
21 Test an error to have a specific message.
22
23 @param expected - Expected message of the Error.
24 */
25 message(expected) {
26 return this.addValidator({
27 message: (error, label) => `Expected ${label} message to be \`${expected}\`, got \`${error.message}\``,
28 validator: error => error.message === expected,
29 });
30 }
31 /**
32 Test the error message to include a specific message.
33
34 @param message - Message that should be included in the error.
35 */
36 messageIncludes(message) {
37 return this.addValidator({
38 message: (error, label) => `Expected ${label} message to include \`${message}\`, got \`${error.message}\``,
39 validator: error => error.message.includes(message),
40 });
41 }
42 /**
43 Test the error object to have specific keys.
44
45 @param keys - One or more keys which should be part of the error object.
46 */
47 hasKeys(...keys) {
48 return this.addValidator({
49 message: (_, label) => `Expected ${label} message to have keys \`${keys.join('`, `')}\``,
50 validator: error => keys.every(key => Object.hasOwn(error, key)),
51 });
52 }
53 /**
54 Test an error to be of a specific instance type.
55
56 @param instance - The expected instance type of the error.
57 */
58 instanceOf(instance) {
59 return this.addValidator({
60 message: (error, label) => `Expected ${label} \`${error.name}\` to be of type \`${instance.name}\``,
61 validator: error => error instanceof instance,
62 });
63 }
64 /**
65 Test an Error to be a TypeError.
66 */
67 get typeError() {
68 return this.instanceOf(TypeError);
69 }
70 /**
71 Test an Error to be an EvalError.
72 */
73 get evalError() {
74 return this.instanceOf(EvalError);
75 }
76 /**
77 Test an Error to be a RangeError.
78 */
79 get rangeError() {
80 return this.instanceOf(RangeError);
81 }
82 /**
83 Test an Error to be a ReferenceError.
84 */
85 get referenceError() {
86 return this.instanceOf(ReferenceError);
87 }
88 /**
89 Test an Error to be a SyntaxError.
90 */
91 get syntaxError() {
92 return this.instanceOf(SyntaxError);
93 }
94 /**
95 Test an Error to be a URIError.
96 */
97 get uriError() {
98 return this.instanceOf(URIError);
99 }
100}