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

Add support for timers/promises module from nodejs #495

Merged
merged 2 commits into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ clock instance, not the browser's internals.

Calling `install` with no arguments achieves this. You can call `uninstall`
later to restore things as they were again.
Note that in NodeJS also the [timers](https://nodejs.org/api/timers.html) module will receive fake timers when using global scope.
Note that in NodeJS the [timers](https://nodejs.org/api/timers.html) and [timers/promises](https://nodejs.org/api/timers.html#timers-promises-api) modules will also receive fake timers when using global scope.

```js
// In the browser distribution, a global `FakeTimers` is already available
Expand Down Expand Up @@ -148,7 +148,7 @@ The `loopLimit` argument sets the maximum number of timers that will be run when
### `var clock = FakeTimers.install([config])`

Installs FakeTimers using the specified config (otherwise with epoch `0` on the global scope).
Note that in NodeJS also the [timers](https://nodejs.org/api/timers.html) module will receive fake timers when using global scope.
Note that in NodeJS the [timers](https://nodejs.org/api/timers.html) and [timers/promises](https://nodejs.org/api/timers.html#timers-promises-api) modules will also receive fake timers when using global scope.
The following configuration options are available

| Parameter | Type | Default | Description |
Expand Down
243 changes: 242 additions & 1 deletion src/fake-timers-src.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
"use strict";

const globalObject = require("@sinonjs/commons").global;
let timersModule;
let timersModule, timersPromisesModule;
if (typeof require === "function" && typeof module === "object") {
try {
timersModule = require("timers");
} catch (e) {
// ignored
}
try {
timersPromisesModule = require("timers/promises");
} catch (e) {
// ignored
}
}

/**
Expand Down Expand Up @@ -47,13 +52,13 @@

/**
* @typedef RequestAnimationFrame
* @property {function(number):void} requestAnimationFrame

Check warning on line 55 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

Missing JSDoc @Property "requestAnimationFrame" description
* @returns {number} - the id
*/

/**
* @typedef Performance
* @property {function(): number} now

Check warning on line 61 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

Missing JSDoc @Property "now" description
*/

/* eslint-disable jsdoc/require-property-description */
Expand Down Expand Up @@ -94,6 +99,7 @@
* @property {Function[]} methods - the methods that are faked
* @property {boolean} [shouldClearNativeTimers] inherited from config
* @property {{methodName:string, original:any}[] | undefined} timersModuleMethods
* @property {{methodName:string, original:any}[] | undefined} timersPromisesModuleMethods
*/
/* eslint-enable jsdoc/require-property-description */

Expand Down Expand Up @@ -330,7 +336,7 @@
return timer && timer.callAt >= from && timer.callAt <= to;
}

/**

Check warning on line 339 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

Missing JSDoc @returns declaration
* @param {Clock} clock
* @param {Timer} job
*/
Expand Down Expand Up @@ -681,7 +687,7 @@
}

/* eslint consistent-return: "off" */
/**

Check warning on line 690 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

JSDoc @returns declaration present but return expression not available in function
* Timer comparitor
*
* @param {Timer} a
Expand Down Expand Up @@ -813,7 +819,7 @@
}
}

/**

Check warning on line 822 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

Missing JSDoc @returns declaration
* Gets clear handler name for a given timer type
*
* @param {string} ttype
Expand All @@ -825,7 +831,7 @@
return `clear${ttype}`;
}

/**

Check warning on line 834 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

Missing JSDoc @returns declaration
* Gets schedule handler name for a given timer type
*
* @param {string} ttype
Expand All @@ -837,7 +843,7 @@
return `set${ttype}`;
}

/**

Check warning on line 846 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

Missing JSDoc @returns declaration
* Creates an anonymous function to warn only once
*/
function createWarnOnce() {
Expand All @@ -849,7 +855,7 @@
}
const warnOnce = createWarnOnce();

/**

Check warning on line 858 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

Missing JSDoc @returns declaration
* @param {Clock} clock
* @param {number} timerId
* @param {string} ttype
Expand Down Expand Up @@ -954,6 +960,16 @@
timersModule[entry.methodName] = entry.original;
}
}
if (clock.timersPromisesModuleMethods !== undefined) {
for (
let j = 0;
j < clock.timersPromisesModuleMethods.length;
j++
) {
const entry = clock.timersPromisesModuleMethods[j];
timersPromisesModule[entry.methodName] = entry.original;
}
}
}

if (config.shouldAdvanceTime === true) {
Expand Down Expand Up @@ -1038,8 +1054,8 @@

/**
* @typedef {object} Timers
* @property {setTimeout} setTimeout

Check warning on line 1057 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

Missing JSDoc @Property "setTimeout" description
* @property {clearTimeout} clearTimeout

Check warning on line 1058 in src/fake-timers-src.js

View workflow job for this annotation

GitHub Actions / lint

Missing JSDoc @Property "clearTimeout" description
* @property {setInterval} setInterval
* @property {clearInterval} clearInterval
* @property {Date} Date
Expand Down Expand Up @@ -1834,6 +1850,9 @@
if (_global === globalObject && timersModule) {
clock.timersModuleMethods = [];
}
if (_global === globalObject && timersPromisesModule) {
clock.timersPromisesModuleMethods = [];
}
for (i = 0, l = clock.methods.length; i < l; i++) {
const nameOfMethodToReplace = clock.methods[i];

Expand Down Expand Up @@ -1872,6 +1891,228 @@
timersModule[nameOfMethodToReplace] =
_global[nameOfMethodToReplace];
}
if (clock.timersPromisesModuleMethods !== undefined) {
if (nameOfMethodToReplace === "setTimeout") {
clock.timersPromisesModuleMethods.push({
methodName: "setTimeout",
original: timersPromisesModule.setTimeout,
});

timersPromisesModule.setTimeout = (
delay,
value,
options = {},
) =>
new Promise((resolve, reject) => {
const abort = () => {
options.signal.removeEventListener(
"abort",
abort,
);
// This is safe, there is no code path that leads to this function
// being invoked before handle has been assigned.
// eslint-disable-next-line no-use-before-define
clock.clearTimeout(handle);
reject(options.signal.reason);
};

const handle = clock.setTimeout(() => {
if (options.signal) {
options.signal.removeEventListener(
"abort",
abort,
);
}
WhiteAutumn marked this conversation as resolved.
Show resolved Hide resolved

resolve(value);
}, delay);

if (options.signal) {
if (options.signal.aborted) {
abort();
} else {
options.signal.addEventListener(
"abort",
abort,
);
}
}
});
} else if (nameOfMethodToReplace === "setImmediate") {
clock.timersPromisesModuleMethods.push({
methodName: "setImmediate",
original: timersPromisesModule.setImmediate,
});

timersPromisesModule.setImmediate = (value, options = {}) =>
new Promise((resolve, reject) => {
const abort = () => {
options.signal.removeEventListener(
"abort",
abort,
);
// This is safe, there is no code path that leads to this function
// being invoked before handle has been assigned.
// eslint-disable-next-line no-use-before-define
clock.clearImmediate(handle);
reject(options.signal.reason);
};

const handle = clock.setImmediate(() => {
if (options.signal) {
options.signal.removeEventListener(
"abort",
abort,
);
}

resolve(value);
});

if (options.signal) {
if (options.signal.aborted) {
abort();
} else {
options.signal.addEventListener(
"abort",
abort,
);
}
}
});
} else if (nameOfMethodToReplace === "setInterval") {
clock.timersPromisesModuleMethods.push({
methodName: "setInterval",
original: timersPromisesModule.setInterval,
});

timersPromisesModule.setInterval = (
delay,
value,
options = {},
) => ({
[Symbol.asyncIterator]: () => {
const createResolvable = () => {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
promise.resolve = resolve;
promise.reject = reject;
return promise;
};

let done = false;
let hasThrown = false;
let returnCall;
let nextAvailable = 0;
const nextQueue = [];

const handle = clock.setInterval(() => {
if (nextQueue.length > 0) {
nextQueue.shift().resolve();
} else {
nextAvailable++;
}
}, delay);

const abort = () => {
options.signal.removeEventListener(
"abort",
abort,
);
clock.clearInterval(handle);
done = true;
for (const resolvable of nextQueue) {
resolvable.resolve();
}
};

if (options.signal) {
if (options.signal.aborted) {
done = true;
} else {
options.signal.addEventListener(
"abort",
abort,
);
}
}

return {
next: async () => {
if (options.signal) {
if (
options.signal.aborted &&
!hasThrown
) {
hasThrown = true;
throw options.signal.reason;
}
}

if (done) {
return { done: true, value: undefined };
}

if (nextAvailable > 0) {
nextAvailable--;
return { done: false, value: value };
}

const resolvable = createResolvable();
nextQueue.push(resolvable);

await resolvable;

if (returnCall && nextQueue.length === 0) {
returnCall.resolve();
}

if (options.signal) {
if (
options.signal.aborted &&
!hasThrown
) {
hasThrown = true;
throw options.signal.reason;
}
}

if (done) {
return { done: true, value: undefined };
}

return { done: false, value: value };
},
return: async () => {
if (done) {
return { done: true, value: undefined };
}

if (nextQueue.length > 0) {
returnCall = createResolvable();
await returnCall;
}

clock.clearInterval(handle);
done = true;

if (options.signal) {
options.signal.removeEventListener(
"abort",
abort,
);
}

return { done: true, value: undefined };
},
};
},
});
}
}
}

return clock;
Expand Down
Loading
Loading