-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
pingTimer.ts
60 lines (53 loc) · 1.43 KB
/
pingTimer.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 { afterEach, beforeEach, describe, it } from 'node:test'
import PingTimer from '../src/lib/PingTimer'
import { assert } from 'chai'
import { useFakeTimers, spy } from 'sinon'
describe('PingTimer', () => {
let clock: sinon.SinonFakeTimers
beforeEach(() => {
clock = useFakeTimers()
})
afterEach(() => {
clock.restore()
})
it('should schedule and clear', () => {
const keepalive = 10 // seconds
const cb = spy()
const pingTimer = new PingTimer(keepalive, cb, 'auto')
assert.ok(pingTimer['timerId'], 'timer should be created automatically')
clock.tick(keepalive * 1000 + 1)
assert.equal(
cb.callCount,
1,
'should trigger the callback after keepalive seconds',
)
clock.tick(keepalive * 1000 + 1)
assert.equal(cb.callCount, 2, 'should reschedule automatically')
pingTimer.clear()
assert.ok(
!pingTimer['timerId'],
'timer should not exists after clear()',
)
})
it('should not re-schedule if timer has been cleared in check ping', () => {
const keepalive = 10 // seconds
const cb = spy()
const pingTimer = new PingTimer(
keepalive,
() => {
pingTimer.clear()
cb()
},
'auto',
)
clock.tick(keepalive * 1000 + 1)
assert.equal(
cb.callCount,
1,
'should trigger the callback after keepalive seconds',
)
clock.tick(keepalive * 1000 + 1)
assert.equal(cb.callCount, 1, 'should not re-schedule')
assert.ok(!pingTimer['timerId'], 'timer should not exists')
})
})