|
1 | 1 | import { strict as assert } from 'assert'; |
2 | 2 | import { SinonFakeTimers, useFakeTimers, spy } from 'sinon'; |
3 | | -import RedisSocket from './socket'; |
| 3 | +import RedisSocket, { RedisSocketOptions } from './socket'; |
4 | 4 |
|
5 | 5 | describe('Socket', () => { |
| 6 | + function createSocket(options: RedisSocketOptions): RedisSocket { |
| 7 | + const socket = new RedisSocket( |
| 8 | + () => Promise.resolve(), |
| 9 | + options |
| 10 | + ); |
| 11 | + |
| 12 | + socket.on('error', (err) => { |
| 13 | + // ignore errors |
| 14 | + console.log(err); |
| 15 | + }); |
| 16 | + |
| 17 | + return socket; |
| 18 | + } |
| 19 | + |
6 | 20 | describe('reconnectStrategy', () => { |
7 | 21 | let clock: SinonFakeTimers; |
8 | 22 | beforeEach(() => clock = useFakeTimers()); |
9 | 23 | afterEach(() => clock.restore()); |
10 | 24 |
|
11 | | - it('custom strategy', () => { |
12 | | - const reconnectStrategy = spy((retries: number): number | Error => { |
| 25 | + it('custom strategy', async () => { |
| 26 | + const reconnectStrategy = spy((retries: number) => { |
13 | 27 | assert.equal(retries + 1, reconnectStrategy.callCount); |
14 | 28 |
|
15 | | - if (retries === 50) { |
16 | | - return Error('50'); |
17 | | - } |
| 29 | + if (retries === 50) return new Error('50'); |
18 | 30 |
|
19 | 31 | const time = retries * 2; |
20 | 32 | queueMicrotask(() => clock.tick(time)); |
21 | 33 | return time; |
22 | 34 | }); |
23 | 35 |
|
24 | | - const socket = new RedisSocket( |
25 | | - () => Promise.resolve(), |
26 | | - { |
27 | | - host: 'error', |
28 | | - reconnectStrategy |
29 | | - } |
30 | | - ); |
31 | | - |
32 | | - socket.on('error', () => { |
33 | | - // ignore errors |
| 36 | + const socket = createSocket({ |
| 37 | + host: 'error', |
| 38 | + reconnectStrategy |
34 | 39 | }); |
35 | 40 |
|
36 | | - return assert.rejects(socket.connect(), { |
| 41 | + await assert.rejects(socket.connect(), { |
37 | 42 | message: '50' |
38 | 43 | }); |
| 44 | + |
| 45 | + assert.equal(socket.isOpen, false); |
| 46 | + }); |
| 47 | + |
| 48 | + it('should handle errors', async () => { |
| 49 | + const socket = createSocket({ |
| 50 | + host: 'error', |
| 51 | + reconnectStrategy(retries: number) { |
| 52 | + if (retries === 1) return new Error('done'); |
| 53 | + queueMicrotask(() => clock.tick(500)); |
| 54 | + throw new Error(); |
| 55 | + } |
| 56 | + }); |
| 57 | + |
| 58 | + await assert.rejects(socket.connect()); |
| 59 | + |
| 60 | + assert.equal(socket.isOpen, false); |
39 | 61 | }); |
40 | 62 | }); |
41 | 63 | }); |
0 commit comments