Skip to content

Commit 061a903

Browse files
authored
test(spec): SafeEventEmitter
1 parent b0d2817 commit 061a903

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

src/events/spec.test.ts

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* @test SafeEventEmitter
3+
* @spec expect
4+
*/
5+
6+
import SafeEventEmitter from '.';
7+
8+
describe('SafeEventEmitter', () => {
9+
it('can be constructed without error', () => {
10+
expect(new SafeEventEmitter()).toBeDefined();
11+
});
12+
13+
it('can emit a value with no listeners', () => {
14+
const see = new SafeEventEmitter();
15+
expect(see.emit('foo', 42)).toBe(false);
16+
});
17+
18+
it('can emit a value with 1 listeners', () => {
19+
expect.assertions(2);
20+
21+
const see = new SafeEventEmitter();
22+
see.on('foo', (x) => expect(x).toBe(42));
23+
expect(see.emit('foo', 42)).toBe(true);
24+
});
25+
26+
it('can emit a value with 2 listeners', () => {
27+
expect.assertions(3);
28+
29+
const see = new SafeEventEmitter();
30+
see.on('foo', (x) => expect(x).toBe(42));
31+
see.on('foo', (x) => expect(x).toBe(42));
32+
expect(see.emit('foo', 42)).toBe(true);
33+
});
34+
35+
it('returns false when _events is somehow undefined', () => {
36+
const see = new SafeEventEmitter();
37+
see.on('foo', () => { /* */ });
38+
delete (see as any)._events;
39+
expect(see.emit('foo', 42)).toBe(false);
40+
});
41+
42+
it('throws error from handler after setTimeout', () => {
43+
jest.useFakeTimers();
44+
const see = new SafeEventEmitter();
45+
see.on('boom', () => {
46+
throw new Error('foo');
47+
});
48+
expect(() => {
49+
see.emit('boom');
50+
}).not.toThrow();
51+
expect(() => {
52+
jest.runAllTimers();
53+
}).toThrow('foo');
54+
});
55+
56+
it('throws error emitted when there is no error handler', () => {
57+
const see = new SafeEventEmitter();
58+
expect(() => {
59+
see.emit('error', new Error('foo'));
60+
}).toThrow('foo');
61+
});
62+
63+
it('throws error emitted when there is no error handler AND _events is somehow undefined', () => {
64+
const see = new SafeEventEmitter();
65+
delete (see as any)._events;
66+
expect(() => {
67+
see.emit('error', new Error('foo'));
68+
}).toThrow('foo');
69+
});
70+
71+
it('throws default error when there is no error handler and error event emitted', () => {
72+
const see = new SafeEventEmitter();
73+
expect(() => {
74+
see.emit('error');
75+
}).toThrow('Unhandled error.');
76+
});
77+
78+
it('throws error when there is no error handler and error event emitted', () => {
79+
const see = new SafeEventEmitter();
80+
expect(() => {
81+
see.emit('error', { message: 'foo' });
82+
}).toThrow('Unhandled error. (foo)');
83+
});
84+
});

0 commit comments

Comments
 (0)