|
1 | 1 | import {retry, timeout, wait} from '../dist/async-tasks.js' |
| 2 | +import {StableSocket} from '../dist/index.js' |
| 3 | + |
| 4 | +class Delegate { |
| 5 | + constructor(fatal) { |
| 6 | + this.fatal = fatal |
| 7 | + this.states = [] |
| 8 | + } |
| 9 | + socketDidOpen() { |
| 10 | + this.states.push('open') |
| 11 | + } |
| 12 | + socketDidClose() { |
| 13 | + this.states.push('closed') |
| 14 | + } |
| 15 | + socketDidFinish() { |
| 16 | + this.states.push('finished') |
| 17 | + } |
| 18 | + socketDidReceiveMessage(socket, message) { |
| 19 | + this.states.push(`msg:${message}`) |
| 20 | + } |
| 21 | + socketShouldRetry(socket, code) { |
| 22 | + return code !== this.fatal |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +describe('StableSocket', function () { |
| 27 | + it('invokes lifecycle delegate methods', async function () { |
| 28 | + const url = 'ws://localhost:7999' |
| 29 | + const delegate = new Delegate(0) |
| 30 | + const policy = {timeout: 100, attempts: 1, maxDelay: 100} |
| 31 | + const socket = new StableSocket(url, delegate, policy) |
| 32 | + await socket.open() |
| 33 | + assert(socket.isOpen()) |
| 34 | + assert.deepEqual(['open'], delegate.states) |
| 35 | + socket.send('echo:hello') |
| 36 | + await wait(10) |
| 37 | + socket.close() |
| 38 | + assert.deepEqual(['open', 'msg:hello', 'closed', 'finished'], delegate.states) |
| 39 | + }) |
| 40 | + |
| 41 | + it('retries on non-fatal close code', async function () { |
| 42 | + const url = 'ws://localhost:7999' |
| 43 | + const delegate = new Delegate(0) |
| 44 | + const policy = {timeout: 100, attempts: 1, maxDelay: 100} |
| 45 | + const socket = new StableSocket(url, delegate, policy) |
| 46 | + await socket.open() |
| 47 | + assert(socket.isOpen()) |
| 48 | + assert.deepEqual(['open'], delegate.states) |
| 49 | + socket.send('close:1000') |
| 50 | + await wait(200) |
| 51 | + assert.deepEqual(['open', 'closed', 'open'], delegate.states) |
| 52 | + socket.close() |
| 53 | + }) |
| 54 | + |
| 55 | + it('does not retry on fatal close code', async function () { |
| 56 | + const url = 'ws://localhost:7999' |
| 57 | + const delegate = new Delegate(4000) |
| 58 | + const policy = {timeout: 100, attempts: 1, maxDelay: 100} |
| 59 | + const socket = new StableSocket(url, delegate, policy) |
| 60 | + await socket.open() |
| 61 | + assert(socket.isOpen()) |
| 62 | + assert.deepEqual(['open'], delegate.states) |
| 63 | + socket.send('close:4000') |
| 64 | + await wait(200) |
| 65 | + assert.deepEqual(['open', 'closed', 'finished'], delegate.states) |
| 66 | + }) |
| 67 | +}) |
2 | 68 |
|
3 | 69 | describe('async-tasks', function () { |
4 | 70 | describe('timeout', function () { |
|
0 commit comments