Add `customTimers` option (#17)

Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
This commit is contained in:
Pedro Augusto de Paula Barbosa 2020-12-01 12:40:53 -03:00 committed by GitHub
parent 5e4f43cf37
commit 085f437e49
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 114 additions and 9 deletions

39
index.d.ts vendored
View File

@ -5,6 +5,39 @@ declare class TimeoutErrorClass extends Error {
declare namespace pTimeout {
type TimeoutError = TimeoutErrorClass;
type Options = {
/**
Custom implementations for the `setTimeout` and `clearTimeout` functions.
Useful for testing purposes, in particular to work around [`sinon.useFakeTimers()`](https://sinonjs.org/releases/latest/fake-timers/).
@example
```
import pTimeout = require('p-timeout');
import sinon = require('sinon');
(async () => {
const originalSetTimeout = setTimeout;
const originalClearTimeout = clearTimeout;
sinon.useFakeTimers();
// Use `pTimeout` without being affected by `sinon.useFakeTimers()`:
await pTimeout(doSomething(), 2000, undefined, {
customTimers: {
setTimeout: originalSetTimeout,
clearTimeout: originalClearTimeout
}
});
})();
```
*/
readonly customTimers?: {
setTimeout: typeof global.setTimeout;
clearTimeout: typeof global.clearTimeout;
};
}
}
declare const pTimeout: {
@ -32,7 +65,8 @@ declare const pTimeout: {
<ValueType>(
input: PromiseLike<ValueType>,
milliseconds: number,
message?: string | Error
message?: string | Error,
options?: pTimeout.Options
): Promise<ValueType>;
/**
@ -60,7 +94,8 @@ declare const pTimeout: {
<ValueType, ReturnType>(
input: PromiseLike<ValueType>,
milliseconds: number,
fallback: () => ReturnType | Promise<ReturnType>
fallback: () => ReturnType | Promise<ReturnType>,
options?: pTimeout.Options
): Promise<ValueType | ReturnType>;
TimeoutError: typeof TimeoutErrorClass;

View File

@ -9,7 +9,7 @@ class TimeoutError extends Error {
}
}
const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => {
const pTimeout = (promise, milliseconds, fallback, options) => new Promise((resolve, reject) => {
if (typeof milliseconds !== 'number' || milliseconds < 0) {
throw new TypeError('Expected `milliseconds` to be a positive number');
}
@ -19,7 +19,12 @@ const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reje
return;
}
const timer = setTimeout(() => {
options = {
customTimers: {setTimeout, clearTimeout},
...options
};
const timer = options.customTimers.setTimeout(() => {
if (typeof fallback === 'function') {
try {
resolve(fallback());
@ -45,7 +50,7 @@ const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reje
// eslint-disable-next-line promise/prefer-await-to-then
promise.then(resolve, reject),
() => {
clearTimeout(timer);
options.customTimers.clearTimeout(timer);
}
);
});

View File

@ -1,4 +1,4 @@
import {expectType} from 'tsd';
import {expectType, expectError} from 'tsd';
import pTimeout = require('.');
import {TimeoutError} from '.';
@ -23,5 +23,19 @@ pTimeout(delayedPromise(), 50, () => 10).then(value => {
expectType<string | number>(value);
});
const customTimers = {setTimeout, clearTimeout};
pTimeout(delayedPromise(), 50, undefined, {customTimers});
pTimeout(delayedPromise(), 50, 'foo', {customTimers});
pTimeout(delayedPromise(), 50, new Error('error'), {customTimers});
pTimeout(delayedPromise(), 50, () => 10, {});
expectError(pTimeout(delayedPromise(), 50, () => 10, {customTimers: {setTimeout}}));
expectError(pTimeout(delayedPromise(), 50, () => 10, {
customTimers: {
setTimeout: () => 42, // Invalid `setTimeout` implementation
clearTimeout
}
}));
const timeoutError = new TimeoutError();
expectType<TimeoutError>(timeoutError);

View File

@ -39,7 +39,7 @@
"ava": "^1.4.1",
"delay": "^4.1.0",
"p-cancelable": "^2.0.0",
"tsd": "^0.7.2",
"tsd": "^0.13.1",
"xo": "^0.24.0"
}
}

View File

@ -22,8 +22,8 @@ pTimeout(delayedPromise, 50).then(() => 'foo');
## API
### pTimeout(input, milliseconds, message?)
### pTimeout(input, milliseconds, fallback?)
### pTimeout(input, milliseconds, message?, options?)
### pTimeout(input, milliseconds, fallback?, options?)
Returns a decorated `input` that times out after `milliseconds` time.
@ -71,6 +71,40 @@ pTimeout(delayedPromise(), 50, () => {
});
```
#### options
Type: `object`
##### customTimers
Type: `object` with function properties `setTimeout` and `clearTimeout`
Custom implementations for the `setTimeout` and `clearTimeout` functions.
Useful for testing purposes, in particular to work around [`sinon.useFakeTimers()`](https://sinonjs.org/releases/latest/fake-timers/).
Example:
```js
const pTimeout = require('p-timeout');
const sinon = require('sinon');
(async () => {
const originalSetTimeout = setTimeout;
const originalClearTimeout = clearTimeout;
sinon.useFakeTimers();
// Use `pTimeout` without being affected by `sinon.useFakeTimers()`:
await pTimeout(doSomething(), 2000, undefined, {
customTimers: {
setTimeout: originalSetTimeout,
clearTimeout: originalClearTimeout
}
});
})();
```
### pTimeout.TimeoutError
Exposed for instance checking and sub-classing.

17
test.js
View File

@ -55,3 +55,20 @@ test('calls `.cancel()` on promise when it exists', async t => {
await t.throwsAsync(pTimeout(promise, 50), pTimeout.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);
}
}
});
});