-
Notifications
You must be signed in to change notification settings - Fork 542
/
assert.test.ts
60 lines (52 loc) · 1.78 KB
/
assert.test.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
59
60
import { assertStruct } from './assert';
import { EventStruct } from './notification';
describe('assertStruct', () => {
it('does not throw for a valid value', () => {
expect(() =>
assertStruct({ name: 'foo', data: 'bar' }, EventStruct),
).not.toThrow();
});
it('throws meaningful error messages for an invalid value', () => {
expect(() => assertStruct({ data: 'foo' }, EventStruct)).toThrow(
'Assertion failed: At path: name -- Expected a string, but received: undefined.',
);
expect(() => assertStruct({ name: 1, data: 'foo' }, EventStruct)).toThrow(
'Assertion failed: At path: name -- Expected a string, but received: 1.',
);
});
it('throws with a custom error prefix', () => {
expect(() =>
assertStruct({ data: 'foo' }, EventStruct, 'Invalid event'),
).toThrow(
'Invalid event: At path: name -- Expected a string, but received: undefined.',
);
});
it('throws with a custom error class', () => {
class CustomError extends Error {
constructor({ message }: { message: string }) {
super(message);
this.name = 'CustomError';
}
}
expect(() =>
assertStruct({ data: 'foo' }, EventStruct, 'Invalid event', CustomError),
).toThrow(
new CustomError({
message:
'Invalid event: At path: name -- Expected a string, but received: undefined.',
}),
);
});
it('throws with a custom error function', () => {
const CustomError = ({ message }: { message: string }) =>
new Error(message);
expect(() =>
assertStruct({ data: 'foo' }, EventStruct, 'Invalid event', CustomError),
).toThrow(
CustomError({
message:
'Invalid event: At path: name -- Expected a string, but received: undefined.',
}),
);
});
});