Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix util.promisify(setTimeout) on jest-fake-timers #9180

Merged
merged 13 commits into from Nov 29, 2019
15 changes: 15 additions & 0 deletions packages/jest-fake-timers/src/__tests__/jestFakeTimers.test.ts
Expand Up @@ -8,6 +8,7 @@
import {runInNewContext} from 'vm';
import mock = require('jest-mock');
import FakeTimers from '../jestFakeTimers';
import util = require('util');

const timerConfig = {
idToRef: (id: number) => id,
Expand Down Expand Up @@ -40,6 +41,20 @@ describe('FakeTimers', () => {
expect(global.setTimeout).not.toBe(undefined);
});

it('accepts to promisify setTimeout mock', async () => {
const global = ({process} as unknown) as NodeJS.Global;
const timers = new FakeTimers({
config,
global,
moduleMocker,
timerConfig,
});
timers.useFakeTimers();
const timeoutPromise = util.promisify(global.setTimeout)(0, 'resolved');
timers.runAllTimers();
await expect(timeoutPromise).resolves.toBe('resolved');
});

it('installs clearTimeout mock', () => {
const global = ({process} as unknown) as NodeJS.Global;
const timers = new FakeTimers({
Expand Down
9 changes: 8 additions & 1 deletion packages/jest-fake-timers/src/jestFakeTimers.ts
Expand Up @@ -8,6 +8,7 @@
import {ModuleMocker} from 'jest-mock';
import {StackTraceConfig, formatStackTrace} from 'jest-message-util';
import {setGlobal} from 'jest-util';
import util = require('util');

type Callback = (...args: Array<unknown>) => void;

Expand Down Expand Up @@ -368,6 +369,12 @@ export default class FakeTimers<TimerRef> {
// @ts-ignore TODO: figure out better typings here
this._moduleMocker.fn().mockImplementation(impl);

const promisifiedFakeSetTimeout = fn(this._fakeSetTimeout.bind(this));
jeysal marked this conversation as resolved.
Show resolved Hide resolved
promisifiedFakeSetTimeout[util.promisify.custom] = (
delay?: number,
arg?: any,
) => new Promise(resolve => promisifiedFakeSetTimeout(resolve, delay, arg));

// TODO: add better typings; these are mocks, but typed as regular timers
this._fakeTimerAPIs = {
clearImmediate: fn(this._fakeClearImmediate.bind(this)),
Expand All @@ -376,7 +383,7 @@ export default class FakeTimers<TimerRef> {
nextTick: fn(this._fakeNextTick.bind(this)),
setImmediate: fn(this._fakeSetImmediate.bind(this)),
setInterval: fn(this._fakeSetInterval.bind(this)),
setTimeout: fn(this._fakeSetTimeout.bind(this)),
setTimeout: promisifiedFakeSetTimeout,
};
}

Expand Down