-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
pingTimer.ts
53 lines (46 loc) · 1.38 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
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)
assert.ok(pingTimer['timer'], '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['timer'], '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()
})
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['timer'], 'timer should not exists')
})
})