forked from sindresorhus/p-timeout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
90 lines (73 loc) · 2.56 KB
/
test.js
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
85
86
87
88
89
90
import test from 'ava';
import delay from 'delay';
import PCancelable from 'p-cancelable';
import inRange from 'in-range';
import timeSpan from 'time-span';
import pTimeout, {TimeoutError} from './index.js';
const fixture = Symbol('fixture');
const fixtureError = new Error('fixture');
test('resolves before timeout', async t => {
t.is(await pTimeout(delay(50).then(() => fixture), 200), fixture);
});
test('throws when milliseconds is not number', async t => {
await t.throwsAsync(pTimeout(delay(50), '200'), {instanceOf: TypeError});
});
test('throws when milliseconds is negative number', async t => {
await t.throwsAsync(pTimeout(delay(50), -1), {instanceOf: TypeError});
});
test('throws when milliseconds is NaN', async t => {
await t.throwsAsync(pTimeout(delay(50), Number.NaN), {instanceOf: TypeError});
});
test('handles milliseconds being `Infinity`', async t => {
t.is(
await pTimeout(delay(50, {value: fixture}), Number.POSITIVE_INFINITY),
fixture
);
});
test('rejects after timeout', async t => {
await t.throwsAsync(pTimeout(delay(200), 50), {instanceOf: TimeoutError});
});
test('rejects before timeout if specified promise rejects', async t => {
await t.throwsAsync(pTimeout(delay(50).then(() => Promise.reject(fixtureError)), 200), {message: fixtureError.message});
});
test('fallback argument', async t => {
await t.throwsAsync(pTimeout(delay(200), 50, 'rainbow'), {message: 'rainbow'});
await t.throwsAsync(pTimeout(delay(200), 50, new RangeError('cake')), {instanceOf: RangeError});
await t.throwsAsync(pTimeout(delay(200), 50, () => Promise.reject(fixtureError)), {message: fixtureError.message});
await t.throwsAsync(pTimeout(delay(200), 50, () => {
throw new RangeError('cake');
}), {instanceOf: RangeError});
});
test('calls `.cancel()` on promise when it exists', async t => {
const promise = new PCancelable(async (resolve, reject, onCancel) => {
onCancel(() => {
t.pass();
});
await delay(200);
resolve();
});
await t.throwsAsync(pTimeout(promise, 50), {instanceOf: TimeoutError});
t.true(promise.isCanceled);
});
test('accepts `customTimers` option', async t => {
t.plan(2);
await pTimeout(delay(50), 123, undefined, {
customTimers: {
setTimeout(fn, milliseconds) {
t.is(milliseconds, 123);
return setTimeout(fn, milliseconds);
},
clearTimeout(timeoutId) {
t.pass();
return clearTimeout(timeoutId);
}
}
});
});
test('`.clear()` method', async t => {
const end = timeSpan();
const promise = pTimeout(delay(300), 200);
promise.clear();
await promise;
t.true(inRange(end(), {start: 0, end: 350}));
});