forked from rocicorp/mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsleep.test.ts
More file actions
84 lines (70 loc) · 1.9 KB
/
sleep.test.ts
File metadata and controls
84 lines (70 loc) · 1.9 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import {SinonFakeTimers, useFakeTimers} from 'sinon';
import {afterEach, beforeEach, expect, test} from 'vitest';
import {AbortError} from './abort-error.js';
import {sleep, sleepWithAbort} from './sleep.js';
let clock: SinonFakeTimers;
beforeEach(() => {
clock = useFakeTimers(0);
});
afterEach(() => {
clock.restore();
});
test('sleep', async () => {
let callCount = 0;
const p = (async () => {
await sleep(100);
callCount++;
})();
await clock.tickAsync(99);
expect(Date.now()).toEqual(99);
expect(callCount).toEqual(0);
await clock.tickAsync(1);
expect(callCount).toEqual(1);
expect(Date.now()).toEqual(100);
await clock.tickAsync(100);
expect(callCount).toEqual(1);
expect(Date.now()).toEqual(200);
await p;
expect(Date.now()).toEqual(200);
});
test('sleep abort', async () => {
const controller = new AbortController();
const p = sleep(100, controller.signal);
controller.abort();
let e;
try {
expect(Date.now()).toEqual(0);
await p;
} catch (err) {
e = err;
}
expect(Date.now()).toEqual(0);
expect(e).toBeInstanceOf(AbortError);
await clock.tickAsync(100);
expect(Date.now()).toEqual(100);
await clock.tickAsync(100);
expect(Date.now()).toEqual(200);
});
test('sleepWithAbort', async () => {
let okResolved = false;
let abortedResolved = false;
const controller = new AbortController();
const [p, abortedP] = sleepWithAbort(100, controller.signal);
void p.then(() => {
okResolved = true;
});
void abortedP.then(() => {
abortedResolved = true;
});
await clock.tickAsync(50);
controller.abort();
expect(okResolved).toEqual(false);
expect(abortedResolved).toEqual(false);
expect(Date.now()).toEqual(50);
await clock.tickAsync(0);
expect(okResolved).toEqual(false);
expect(abortedResolved).toEqual(true);
expect(Date.now()).toEqual(50);
await clock.tickAsync(50);
expect(okResolved).toEqual(false);
});