test_runner: add initial draft for fakeTimers

Signed-off-by: Erick Wendel <erick.workspace@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/47775
Backport-PR-URL: https://github.com/nodejs/node/pull/49618
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
This commit is contained in:
Erick Wendel authored and Michaël Zasso committed 2023-10-28 12:24:49 +02:00
1 parent 2b30c8b8a3
commit 05e7f28b40
6 files changed
+1443 -2

No files matched your search

+528
View File
@@ -507,6 +507,116 @@ test('spies on an object method', (t) => {
});
```
### Timers
Mocking timers is a technique commonly used in software testing to simulate and
control the behavior of timers, such as `setInterval` and `setTimeout`,
without actually waiting for the specified time intervals.
Refer to the [`MockTimers`][] class for a full list of methods and features.
This allows developers to write more reliable and
predictable tests for time-dependent functionality.
The example below shows how to mock `setTimeout`.
Using `.enable(['setTimeout']);`
it will mock the `setTimeout` functions in the [node:timers](./timers.md) and
[node:timers/promises](./timers.md#timers-promises-api) modules,
as well as from the Node.js global context.
**Note:** Destructuring functions such as
`import { setTimeout } from 'node:timers'`
is currently not supported by this API.
```mjs
import assert from 'node:assert';
import { mock, test } from 'node:test';
test('mocks setTimeout to be executed synchronously without having to actually wait for it', () => {
const fn = mock.fn();
// Optionally choose what to mock
mock.timers.enable(['setTimeout']);
setTimeout(fn, 9999);
assert.strictEqual(fn.mock.callCount(), 0);
// Advance in time
mock.timers.tick(9999);
assert.strictEqual(fn.mock.callCount(), 1);
// Reset the globally tracked mocks.
mock.timers.reset();
// If you call reset mock instance, it will also reset timers instance
mock.reset();
});
```
```js
const assert = require('node:assert');
const { mock, test } = require('node:test');
test('mocks setTimeout to be executed synchronously without having to actually wait for it', () => {
const fn = mock.fn();
// Optionally choose what to mock
mock.timers.enable(['setTimeout']);
setTimeout(fn, 9999);
assert.strictEqual(fn.mock.callCount(), 0);
// Advance in time
mock.timers.tick(9999);
assert.strictEqual(fn.mock.callCount(), 1);
// Reset the globally tracked mocks.
mock.timers.reset();
// If you call reset mock instance, it'll also reset timers instance
mock.reset();
});
```
The same mocking functionality is also exposed in the mock property on the [`TestContext`][] object
of each test. The benefit of mocking via the test context is
that the test runner will automatically restore all mocked timers
functionality once the test finishes.
```mjs
import assert from 'node:assert';
import { test } from 'node:test';
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
// Optionally choose what to mock
context.mock.timers.enable(['setTimeout']);
setTimeout(fn, 9999);
assert.strictEqual(fn.mock.callCount(), 0);
// Advance in time
context.mock.timers.tick(9999);
assert.strictEqual(fn.mock.callCount(), 1);
});
```
```js
const assert = require('node:assert');
const { test } = require('node:test');
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
// Optionally choose what to mock
context.mock.timers.enable(['setTimeout']);
setTimeout(fn, 9999);
assert.strictEqual(fn.mock.callCount(), 0);
// Advance in time
context.mock.timers.tick(9999);
assert.strictEqual(fn.mock.callCount(), 1);
});
```
## Test reporters
<!-- YAML
@@ -1346,6 +1456,423 @@ added: v18.13.0
This function is syntax sugar for [`MockTracker.method`][] with `options.setter`
set to `true`.
## Class: `MockTimers`
<!-- YAML
added:
- REPLACEME
-->
> Stability: 1 - Experimental
Mocking timers is a technique commonly used in software testing to simulate and
control the behavior of timers, such as `setInterval` and `setTimeout`,
without actually waiting for the specified time intervals.
The [`MockTracker`][] provides a top-level `timers` export
which is a `MockTimers` instance.
### `timers.enable([timers])`
<!-- YAML
added:
- REPLACEME
-->
Enables timer mocking for the specified timers.
* `timers` {Array} An optional array containing the timers to mock.
The currently supported timer values are `'setInterval'` and `'setTimeout'`.
If no array is provided, all timers (`'setInterval'`, `'clearInterval'`, `'setTimeout'`,
and `'clearTimeout'`) will be mocked by default.
**Note:** When you enable mocking for a specific timer, its associated
clear function will also be implicitly mocked.
Example usage:
```mjs
import { mock } from 'node:test';
mock.timers.enable(['setInterval']);
```
```js
const { mock } = require('node:test');
mock.timers.enable(['setInterval']);
```
The above example enables mocking for the `setInterval` timer and
implicitly mocks the `clearInterval` function. Only the `setInterval`
and `clearInterval` functions from [node:timers](./timers.md),
[node:timers/promises](./timers.md#timers-promises-api), and
`globalThis` will be mocked.
Alternatively, if you call `mock.timers.enable()` without any parameters:
All timers (`'setInterval'`, `'clearInterval'`, `'setTimeout'`, and `'clearTimeout'`)
will be mocked. The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout`
functions from `node:timers`, `node:timers/promises`,
and `globalThis` will be mocked.
### `timers.reset()`
<!-- YAML
added:
- REPLACEME
-->
This function restores the default behavior of all mocks that were previously
created by this `MockTimers` instance and disassociates the mocks
from the `MockTracker` instance.
**Note:** After each test completes, this function is called on
the test context's `MockTracker`.
```mjs
import { mock } from 'node:test';
mock.timers.reset();
```
```js
const { mock } = require('node:test');
mock.timers.reset();
```
### `timers.tick(milliseconds)`
<!-- YAML
added:
- REPLACEME
-->
Advances time for all mocked timers.
* `milliseconds` {number} The amount of time, in milliseconds,
to advance the timers.
**Note:** This diverges from how `setTimeout` in Node.js behaves and accepts
only positive numbers. In Node.js, `setTimeout` with negative numbers is
only supported for web compatibility reasons.
The following example mocks a `setTimeout` function and
by using `.tick` advances in
time triggering all pending timers.
```mjs
import assert from 'node:assert';
import { test } from 'node:test';
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
context.mock.timers.enable(['setTimeout']);
setTimeout(fn, 9999);
assert.strictEqual(fn.mock.callCount(), 0);
// Advance in time
context.mock.timers.tick(9999);
assert.strictEqual(fn.mock.callCount(), 1);
});
```
```js
const assert = require('node:assert');
const { test } = require('node:test');
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
context.mock.timers.enable(['setTimeout']);
setTimeout(fn, 9999);
assert.strictEqual(fn.mock.callCount(), 0);
// Advance in time
context.mock.timers.tick(9999);
assert.strictEqual(fn.mock.callCount(), 1);
});
```
Alternativelly, the `.tick` function can be called many times
```mjs
import assert from 'node:assert';
import { test } from 'node:test';
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
context.mock.timers.enable(['setTimeout']);
const nineSecs = 9000;
setTimeout(fn, nineSecs);
const twoSeconds = 3000;
context.mock.timers.tick(twoSeconds);
context.mock.timers.tick(twoSeconds);
context.mock.timers.tick(twoSeconds);
assert.strictEqual(fn.mock.callCount(), 1);
});
```
```js
const assert = require('node:assert');
const { test } = require('node:test');
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
context.mock.timers.enable(['setTimeout']);
const nineSecs = 9000;
setTimeout(fn, nineSecs);
const twoSeconds = 3000;
context.mock.timers.tick(twoSeconds);
context.mock.timers.tick(twoSeconds);
context.mock.timers.tick(twoSeconds);
assert.strictEqual(fn.mock.callCount(), 1);
});
```
#### Using clear functions
As mentioned, all clear functions from timers (`clearTimeout` and `clearInterval`)
are implicity mocked. Take a look at this example using `setTimeout`:
```mjs
import assert from 'node:assert';
import { test } from 'node:test';
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
// Optionally choose what to mock
context.mock.timers.enable(['setTimeout']);
const id = setTimeout(fn, 9999);
// Implicity mocked as well
clearTimeout(id);
context.mock.timers.tick(9999);
// As that setTimeout was cleared the mock function will never be called
assert.strictEqual(fn.mock.callCount(), 0);
});
```
```js
const assert = require('node:assert');
const { test } = require('node:test');
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
// Optionally choose what to mock
context.mock.timers.enable(['setTimeout']);
const id = setTimeout(fn, 9999);
// Implicity mocked as well
clearTimeout(id);
context.mock.timers.tick(9999);
// As that setTimeout was cleared the mock function will never be called
assert.strictEqual(fn.mock.callCount(), 0);
});
```
#### Working with Node.js timers modules
Once you enable mocking timers, [node:timers](./timers.md),
[node:timers/promises](./timers.md#timers-promises-api) modules,
and timers from the Node.js global context are enabled:
**Note:** Destructuring functions such as
`import { setTimeout } from 'node:timers'` is currently
not supported by this API.
```mjs
import assert from 'node:assert';
import { test } from 'node:test';
import nodeTimers from 'node:timers';
import nodeTimersPromises from 'node:timers/promises';
test('mocks setTimeout to be executed synchronously without having to actually wait for it', async (context) => {
const globalTimeoutObjectSpy = context.mock.fn();
const nodeTimerSpy = context.mock.fn();
const nodeTimerPromiseSpy = context.mock.fn();
// Optionally choose what to mock
context.mock.timers.enable(['setTimeout']);
setTimeout(globalTimeoutObjectSpy, 9999);
nodeTimers.setTimeout(nodeTimerSpy, 9999);
const promise = nodeTimersPromises.setTimeout(9999).then(nodeTimerPromiseSpy);
// Advance in time
context.mock.timers.tick(9999);
assert.strictEqual(globalTimeoutObjectSpy.mock.callCount(), 1);
assert.strictEqual(nodeTimerSpy.mock.callCount(), 1);
await promise;
assert.strictEqual(nodeTimerPromiseSpy.mock.callCount(), 1);
});
```
```js
const assert = require('node:assert');
const { test } = require('node:test');
const nodeTimers = require('node:timers');
const nodeTimersPromises = require('node:timers/promises');
test('mocks setTimeout to be executed synchronously without having to actually wait for it', async (context) => {
const globalTimeoutObjectSpy = context.mock.fn();
const nodeTimerSpy = context.mock.fn();
const nodeTimerPromiseSpy = context.mock.fn();
// Optionally choose what to mock
context.mock.timers.enable(['setTimeout']);
setTimeout(globalTimeoutObjectSpy, 9999);
nodeTimers.setTimeout(nodeTimerSpy, 9999);
const promise = nodeTimersPromises.setTimeout(9999).then(nodeTimerPromiseSpy);
// Advance in time
context.mock.timers.tick(9999);
assert.strictEqual(globalTimeoutObjectSpy.mock.callCount(), 1);
assert.strictEqual(nodeTimerSpy.mock.callCount(), 1);
await promise;
assert.strictEqual(nodeTimerPromiseSpy.mock.callCount(), 1);
});
```
In Node.js, `setInterval` from [node:timers/promises](./timers.md#timers-promises-api)
is an `AsyncGenerator` and is also supported by this API:
```mjs
import assert from 'node:assert';
import { test } from 'node:test';
import nodeTimersPromises from 'node:timers/promises';
test('should tick five times testing a real use case', async (context) => {
context.mock.timers.enable(['setInterval']);
const expectedIterations = 3;
const interval = 1000;
const startedAt = Date.now();
async function run() {
const times = [];
for await (const time of nodeTimersPromises.setInterval(interval, startedAt)) {
times.push(time);
if (times.length === expectedIterations) break;
}
return times;
}
const r = run();
context.mock.timers.tick(interval);
context.mock.timers.tick(interval);
context.mock.timers.tick(interval);
const timeResults = await r;
assert.strictEqual(timeResults.length, expectedIterations);
for (let it = 1; it < expectedIterations; it++) {
assert.strictEqual(timeResults[it - 1], startedAt + (interval * it));
}
});
```
```js
const assert = require('node:assert');
const { test } = require('node:test');
const nodeTimersPromises = require('node:timers/promises');
test('should tick five times testing a real use case', async (context) => {
context.mock.timers.enable(['setInterval']);
const expectedIterations = 3;
const interval = 1000;
const startedAt = Date.now();
async function run() {
const times = [];
for await (const time of nodeTimersPromises.setInterval(interval, startedAt)) {
times.push(time);
if (times.length === expectedIterations) break;
}
return times;
}
const r = run();
context.mock.timers.tick(interval);
context.mock.timers.tick(interval);
context.mock.timers.tick(interval);
const timeResults = await r;
assert.strictEqual(timeResults.length, expectedIterations);
for (let it = 1; it < expectedIterations; it++) {
assert.strictEqual(timeResults[it - 1], startedAt + (interval * it));
}
});
```
### `timers.runAll()`
<!-- YAML
added:
- REPLACEME
-->
Triggers all pending mocked timers immediately.
The example below triggers all pending timers immediately,
causing them to execute without any delay.
```mjs
import assert from 'node:assert';
import { test } from 'node:test';
test('runAll functions following the given order', (context) => {
context.mock.timers.enable(['setTimeout']);
const results = [];
setTimeout(() => results.push(1), 9999);
// Notice that if both timers have the same timeout,
// the order of execution is guaranteed
setTimeout(() => results.push(3), 8888);
setTimeout(() => results.push(2), 8888);
assert.deepStrictEqual(results, []);
context.mock.timers.runAll();
assert.deepStrictEqual(results, [3, 2, 1]);
});
```
```js
const assert = require('node:assert');
const { test } = require('node:test');
test('runAll functions following the given order', (context) => {
context.mock.timers.enable(['setTimeout']);
const results = [];
setTimeout(() => results.push(1), 9999);
// Notice that if both timers have the same timeout,
// the order of execution is guaranteed
setTimeout(() => results.push(3), 8888);
setTimeout(() => results.push(2), 8888);
assert.deepStrictEqual(results, []);
context.mock.timers.runAll();
assert.deepStrictEqual(results, [3, 2, 1]);
});
```
**Note:** The `runAll()` function is specifically designed for
triggering timers in the context of timer mocking.
It does not have any effect on real-time system
clocks or actual timers outside of the mocking environment.
## Class: `TestsStream`
<!-- YAML
@@ -1822,6 +2349,7 @@ added: v18.7.0
[`--test-reporter`]: cli.md#--test-reporter
[`--test`]: cli.md#--test
[`MockFunctionContext`]: #class-mockfunctioncontext
[`MockTimers`]: #class-mocktimers
[`MockTracker.method`]: #mockmethodobject-methodname-implementation-options
[`MockTracker`]: #class-mocktracker
[`NODE_V8_COVERAGE`]: cli.md#node_v8_coveragedir
@@ -26,6 +26,7 @@ const {
validateInteger,
validateObject,
} = require('internal/validators');
const { MockTimers } = require('internal/test_runner/mock/mock_timers');
function kDefaultFunction() {}
@@ -106,6 +107,12 @@ delete MockFunctionContext.prototype.nextImpl;
class MockTracker {
#mocks = [];
#timers;
get timers() {
this.#timers ??= new MockTimers();
return this.#timers;
}
fn(
original = function() {},
@@ -265,6 +272,7 @@ class MockTracker {
reset() {
this.restoreAll();
this.#timers?.reset();
this.#mocks = [];
}
@@ -0,0 +1,335 @@
'use strict';
const {
emitExperimentalWarning,
} = require('internal/util');
const {
ArrayPrototypeForEach,
ArrayPrototypeIncludes,
DateNow,
FunctionPrototypeApply,
FunctionPrototypeBind,
Promise,
SymbolAsyncIterator,
globalThis,
} = primordials;
const {
validateAbortSignal,
validateArray,
} = require('internal/validators');
const {
AbortError,
codes: {
ERR_INVALID_STATE,
ERR_INVALID_ARG_VALUE,
},
} = require('internal/errors');
const PriorityQueue = require('internal/priority_queue');
const nodeTimers = require('timers');
const nodeTimersPromises = require('timers/promises');
const EventEmitter = require('events');
function compareTimersLists(a, b) {
return (a.runAt - b.runAt) || (a.id - b.id);
}
function setPosition(node, pos) {
node.priorityQueuePosition = pos;
}
function abortIt(signal) {
return new AbortError(undefined, { cause: signal.reason });
}
const SUPPORTED_TIMERS = ['setTimeout', 'setInterval'];
class MockTimers {
#realSetTimeout;
#realClearTimeout;
#realSetInterval;
#realClearInterval;
#realPromisifiedSetTimeout;
#realPromisifiedSetInterval;
#realTimersSetTimeout;
#realTimersClearTimeout;
#realTimersSetInterval;
#realTimersClearInterval;
#timersInContext = [];
#isEnabled = false;
#currentTimer = 1;
#now = DateNow();
#executionQueue = new PriorityQueue(compareTimersLists, setPosition);
#setTimeout = FunctionPrototypeBind(this.#createTimer, this, false);
#clearTimeout = FunctionPrototypeBind(this.#clearTimer, this);
#setInterval = FunctionPrototypeBind(this.#createTimer, this, true);
#clearInterval = FunctionPrototypeBind(this.#clearTimer, this);
constructor() {
emitExperimentalWarning('The MockTimers API');
}
#createTimer(isInterval, callback, delay, ...args) {
const timerId = this.#currentTimer++;
this.#executionQueue.insert({
__proto__: null,
id: timerId,
callback,
runAt: this.#now + delay,
interval: isInterval,
args,
});
return timerId;
}
#clearTimer(position) {
this.#executionQueue.removeAt(position);
}
async * #setIntervalPromisified(interval, startTime, options) {
const context = this;
const emitter = new EventEmitter();
if (options?.signal) {
validateAbortSignal(options.signal, 'options.signal');
if (options.signal?.aborted) {
throw abortIt(options.signal);
}
const onAbort = (reason) => {
emitter.emit('data', { __proto__: null, aborted: true, reason });
};
options.signal?.addEventListener('abort', onAbort, {
__proto__: null,
once: true,
});
}
const eventIt = EventEmitter.on(emitter, 'data');
const callback = () => {
startTime += interval;
emitter.emit('data', startTime);
};
const timerId = this.#createTimer(true, callback, interval, options);
const clearListeners = () => {
emitter.removeAllListeners();
context.#clearTimer(timerId);
};
const iterator = {
__proto__: null,
[SymbolAsyncIterator]() {
return this;
},
async next() {
const result = await eventIt.next();
const value = result.value[0];
if (value?.aborted) {
iterator.return();
throw abortIt(options.signal);
}
return {
__proto__: null,
done: result.done,
value,
};
},
async return() {
clearListeners();
return eventIt.return();
},
};
yield* iterator;
}
#setTimeoutPromisified(ms, result, options) {
return new Promise((resolve, reject) => {
if (options?.signal) {
try {
validateAbortSignal(options.signal, 'options.signal');
} catch (err) {
return reject(err);
}
if (options.signal?.aborted) {
return reject(abortIt(options.signal));
}
}
const onabort = () => {
this.#clearTimeout(id);
return reject(abortIt(options.signal));
};
const id = this.#setTimeout(() => {
return resolve(result || id);
}, ms);
options?.signal?.addEventListener('abort', onabort, {
__proto__: null,
once: true,
});
});
}
#toggleEnableTimers(activate) {
const options = {
toFake: {
setTimeout: () => {
this.#realSetTimeout = globalThis.setTimeout;
this.#realClearTimeout = globalThis.clearTimeout;
this.#realTimersSetTimeout = nodeTimers.setTimeout;
this.#realTimersClearTimeout = nodeTimers.clearTimeout;
this.#realPromisifiedSetTimeout = nodeTimersPromises.setTimeout;
globalThis.setTimeout = this.#setTimeout;
globalThis.clearTimeout = this.#clearTimeout;
nodeTimers.setTimeout = this.#setTimeout;
nodeTimers.clearTimeout = this.#clearTimeout;
nodeTimersPromises.setTimeout = FunctionPrototypeBind(
this.#setTimeoutPromisified,
this,
);
},
setInterval: () => {
this.#realSetInterval = globalThis.setInterval;
this.#realClearInterval = globalThis.clearInterval;
this.#realTimersSetInterval = nodeTimers.setInterval;
this.#realTimersClearInterval = nodeTimers.clearInterval;
this.#realPromisifiedSetInterval = nodeTimersPromises.setInterval;
globalThis.setInterval = this.#setInterval;
globalThis.clearInterval = this.#clearInterval;
nodeTimers.setInterval = this.#setInterval;
nodeTimers.clearInterval = this.#clearInterval;
nodeTimersPromises.setInterval = FunctionPrototypeBind(
this.#setIntervalPromisified,
this,
);
},
},
toReal: {
setTimeout: () => {
globalThis.setTimeout = this.#realSetTimeout;
globalThis.clearTimeout = this.#realClearTimeout;
nodeTimers.setTimeout = this.#realTimersSetTimeout;
nodeTimers.clearTimeout = this.#realTimersClearTimeout;
nodeTimersPromises.setTimeout = this.#realPromisifiedSetTimeout;
},
setInterval: () => {
globalThis.setInterval = this.#realSetInterval;
globalThis.clearInterval = this.#realClearInterval;
nodeTimers.setInterval = this.#realTimersSetInterval;
nodeTimers.clearInterval = this.#realTimersClearInterval;
nodeTimersPromises.setInterval = this.#realPromisifiedSetInterval;
},
},
};
const target = activate ? options.toFake : options.toReal;
ArrayPrototypeForEach(this.#timersInContext, (timer) => target[timer]());
this.#isEnabled = activate;
}
tick(time = 1) {
if (!this.#isEnabled) {
throw new ERR_INVALID_STATE(
'You should enable MockTimers first by calling the .enable function',
);
}
if (time < 0) {
throw new ERR_INVALID_ARG_VALUE(
'time',
'positive integer',
time,
);
}
this.#now += time;
let timer = this.#executionQueue.peek();
while (timer) {
if (timer.runAt > this.#now) break;
FunctionPrototypeApply(timer.callback, undefined, timer.args);
this.#executionQueue.shift();
if (timer.interval) {
timer.runAt += timer.interval;
this.#executionQueue.insert(timer);
return;
}
timer = this.#executionQueue.peek();
}
}
enable(timers = SUPPORTED_TIMERS) {
if (this.#isEnabled) {
throw new ERR_INVALID_STATE(
'MockTimers is already enabled!',
);
}
validateArray(timers, 'timers');
// Check that the timers passed are supported
ArrayPrototypeForEach(timers, (timer) => {
if (!ArrayPrototypeIncludes(SUPPORTED_TIMERS, timer)) {
throw new ERR_INVALID_ARG_VALUE(
'timers',
timer,
`option ${timer} is not supported`,
);
}
});
this.#timersInContext = timers;
this.#now = DateNow();
this.#toggleEnableTimers(true);
}
reset() {
// Ignore if not enabled
if (!this.#isEnabled) return;
this.#toggleEnableTimers(false);
this.#timersInContext = [];
let timer = this.#executionQueue.peek();
while (timer) {
this.#executionQueue.shift();
timer = this.#executionQueue.peek();
}
}
runAll() {
if (!this.#isEnabled) {
throw new ERR_INVALID_STATE(
'You should enable MockTimers first by calling the .enable function',
);
}
this.tick(Infinity);
}
}
module.exports = { MockTimers };
+1 -1
View File
@@ -31,7 +31,7 @@ const {
},
AbortError,
} = require('internal/errors');
const { MockTracker } = require('internal/test_runner/mock');
const { MockTracker } = require('internal/test_runner/mock/mock');
const { TestsStream } = require('internal/test_runner/tests_stream');
const {
createDeferredCallback,
+1 -1
View File
@@ -23,7 +23,7 @@ ObjectDefineProperty(module.exports, 'mock', {
enumerable: true,
get() {
if (lazyMock === undefined) {
const { MockTracker } = require('internal/test_runner/mock');
const { MockTracker } = require('internal/test_runner/mock/mock');
lazyMock = new MockTracker();
}
+570
View File
@@ -0,0 +1,570 @@
'use strict';
process.env.NODE_TEST_KNOWN_GLOBALS = 0;
const common = require('../common');
const assert = require('node:assert');
const { it, mock, describe } = require('node:test');
const nodeTimers = require('node:timers');
const nodeTimersPromises = require('node:timers/promises');
describe('Mock Timers Test Suite', () => {
describe('MockTimers API', () => {
it('should throw an error if trying to enable a timer that is not supported', (t) => {
assert.throws(() => {
t.mock.timers.enable(['DOES_NOT_EXIST']);
}, {
code: 'ERR_INVALID_ARG_VALUE',
});
});
it('should throw an error if trying to enable a timer twice', (t) => {
t.mock.timers.enable();
assert.throws(() => {
t.mock.timers.enable();
}, {
code: 'ERR_INVALID_STATE',
});
});
it('should not throw if calling reset without enabling timers', (t) => {
t.mock.timers.reset();
});
it('should throw an error if calling tick without enabling timers', (t) => {
assert.throws(() => {
t.mock.timers.tick();
}, {
code: 'ERR_INVALID_STATE',
});
});
it('should throw an error if calling tick with a negative number', (t) => {
t.mock.timers.enable();
assert.throws(() => {
t.mock.timers.tick(-1);
}, {
code: 'ERR_INVALID_ARG_VALUE',
});
});
it('should reset all timers when calling .reset function', (t) => {
t.mock.timers.enable();
const fn = t.mock.fn();
global.setTimeout(fn, 1000);
t.mock.timers.reset();
assert.throws(() => {
t.mock.timers.tick(1000);
}, {
code: 'ERR_INVALID_STATE',
});
assert.strictEqual(fn.mock.callCount(), 0);
});
it('should execute in order if timeout is the same', (t) => {
t.mock.timers.enable();
const order = [];
const fn1 = t.mock.fn(() => order.push('f1'));
const fn2 = t.mock.fn(() => order.push('f2'));
global.setTimeout(fn1, 1000);
global.setTimeout(fn2, 1000);
t.mock.timers.tick(1000);
assert.strictEqual(fn1.mock.callCount(), 1);
assert.strictEqual(fn2.mock.callCount(), 1);
assert.deepStrictEqual(order, ['f1', 'f2']);
});
describe('runAll Suite', () => {
it('should throw an error if calling runAll without enabling timers', (t) => {
assert.throws(() => {
t.mock.timers.runAll();
}, {
code: 'ERR_INVALID_STATE',
});
});
it('should trigger all timers when calling .runAll function', async (t) => {
const timeoutFn = t.mock.fn();
const intervalFn = t.mock.fn();
t.mock.timers.enable();
global.setTimeout(timeoutFn, 1111);
const id = global.setInterval(intervalFn, 9999);
t.mock.timers.runAll();
global.clearInterval(id);
assert.strictEqual(timeoutFn.mock.callCount(), 1);
assert.strictEqual(intervalFn.mock.callCount(), 1);
});
});
});
describe('globals/timers', () => {
describe('setTimeout Suite', () => {
it('should advance in time and trigger timers when calling the .tick function', (t) => {
mock.timers.enable(['setTimeout']);
const fn = mock.fn();
global.setTimeout(fn, 4000);
mock.timers.tick(4000);
assert.strictEqual(fn.mock.callCount(), 1);
mock.timers.reset();
});
it('should advance in time and trigger timers when calling the .tick function multiple times', (t) => {
t.mock.timers.enable(['setTimeout']);
const fn = t.mock.fn();
global.setTimeout(fn, 2000);
t.mock.timers.tick(1000);
assert.strictEqual(fn.mock.callCount(), 0);
t.mock.timers.tick(500);
assert.strictEqual(fn.mock.callCount(), 0);
t.mock.timers.tick(500);
assert.strictEqual(fn.mock.callCount(), 1);
});
it('should work with the same params as the original setTimeout', (t) => {
t.mock.timers.enable(['setTimeout']);
const fn = t.mock.fn();
const args = ['a', 'b', 'c'];
global.setTimeout(fn, 2000, ...args);
t.mock.timers.tick(1000);
t.mock.timers.tick(500);
t.mock.timers.tick(500);
assert.strictEqual(fn.mock.callCount(), 1);
assert.deepStrictEqual(fn.mock.calls[0].arguments, args);
});
it('should keep setTimeout working if timers are disabled', (t, done) => {
const now = Date.now();
const timeout = 2;
const expected = () => now - timeout;
global.setTimeout(common.mustCall(() => {
assert.strictEqual(now - timeout, expected());
done();
}), timeout);
});
});
describe('clearTimeout Suite', () => {
it('should not advance in time if clearTimeout was invoked', (t) => {
t.mock.timers.enable(['setTimeout']);
const fn = mock.fn();
const id = global.setTimeout(fn, 4000);
global.clearTimeout(id);
t.mock.timers.tick(4000);
assert.strictEqual(fn.mock.callCount(), 0);
});
});
describe('setInterval Suite', () => {
it('should tick three times using fake setInterval', (t) => {
t.mock.timers.enable(['setInterval']);
const fn = t.mock.fn();
const id = global.setInterval(fn, 200);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
global.clearInterval(id);
assert.strictEqual(fn.mock.callCount(), 3);
});
it('should work with the same params as the original setInterval', (t) => {
t.mock.timers.enable(['setInterval']);
const fn = t.mock.fn();
const args = ['a', 'b', 'c'];
const id = global.setInterval(fn, 200, ...args);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
global.clearInterval(id);
assert.strictEqual(fn.mock.callCount(), 3);
assert.deepStrictEqual(fn.mock.calls[0].arguments, args);
assert.deepStrictEqual(fn.mock.calls[1].arguments, args);
assert.deepStrictEqual(fn.mock.calls[2].arguments, args);
});
});
describe('clearInterval Suite', () => {
it('should not advance in time if clearInterval was invoked', (t) => {
t.mock.timers.enable(['setInterval']);
const fn = mock.fn();
const id = global.setInterval(fn, 200);
global.clearInterval(id);
t.mock.timers.tick(200);
assert.strictEqual(fn.mock.callCount(), 0);
});
});
});
describe('timers Suite', () => {
describe('setTimeout Suite', () => {
it('should advance in time and trigger timers when calling the .tick function multiple times', (t) => {
t.mock.timers.enable(['setTimeout']);
const fn = t.mock.fn();
const { setTimeout } = nodeTimers;
setTimeout(fn, 2000);
t.mock.timers.tick(1000);
t.mock.timers.tick(500);
t.mock.timers.tick(500);
assert.strictEqual(fn.mock.callCount(), 1);
});
it('should work with the same params as the original timers.setTimeout', (t) => {
t.mock.timers.enable(['setTimeout']);
const fn = t.mock.fn();
const { setTimeout } = nodeTimers;
const args = ['a', 'b', 'c'];
setTimeout(fn, 2000, ...args);
t.mock.timers.tick(1000);
t.mock.timers.tick(500);
t.mock.timers.tick(500);
assert.strictEqual(fn.mock.callCount(), 1);
assert.deepStrictEqual(fn.mock.calls[0].arguments, args);
});
});
describe('clearTimeout Suite', () => {
it('should not advance in time if clearTimeout was invoked', (t) => {
t.mock.timers.enable(['setTimeout']);
const fn = mock.fn();
const { setTimeout, clearTimeout } = nodeTimers;
const id = setTimeout(fn, 2000);
clearTimeout(id);
t.mock.timers.tick(2000);
assert.strictEqual(fn.mock.callCount(), 0);
});
});
describe('setInterval Suite', () => {
it('should tick three times using fake setInterval', (t) => {
t.mock.timers.enable(['setInterval']);
const fn = t.mock.fn();
const id = nodeTimers.setInterval(fn, 200);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
nodeTimers.clearInterval(id);
assert.strictEqual(fn.mock.callCount(), 4);
});
it('should work with the same params as the original timers.setInterval', (t) => {
t.mock.timers.enable(['setInterval']);
const fn = t.mock.fn();
const args = ['a', 'b', 'c'];
const id = nodeTimers.setInterval(fn, 200, ...args);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
t.mock.timers.tick(200);
nodeTimers.clearInterval(id);
assert.strictEqual(fn.mock.callCount(), 4);
assert.deepStrictEqual(fn.mock.calls[0].arguments, args);
assert.deepStrictEqual(fn.mock.calls[1].arguments, args);
assert.deepStrictEqual(fn.mock.calls[2].arguments, args);
assert.deepStrictEqual(fn.mock.calls[3].arguments, args);
});
});
describe('clearInterval Suite', () => {
it('should not advance in time if clearInterval was invoked', (t) => {
t.mock.timers.enable(['setInterval']);
const fn = mock.fn();
const { setInterval, clearInterval } = nodeTimers;
const id = setInterval(fn, 200);
clearInterval(id);
t.mock.timers.tick(200);
assert.strictEqual(fn.mock.callCount(), 0);
});
});
});
describe('timers/promises', () => {
describe('setTimeout Suite', () => {
it('should advance in time and trigger timers when calling the .tick function multiple times', async (t) => {
t.mock.timers.enable(['setTimeout']);
const p = nodeTimersPromises.setTimeout(2000);
t.mock.timers.tick(1000);
t.mock.timers.tick(500);
t.mock.timers.tick(500);
t.mock.timers.tick(500);
p.then(common.mustCall((result) => {
assert.ok(result);
}));
});
it('should work with the same params as the original timers/promises/setTimeout', async (t) => {
t.mock.timers.enable(['setTimeout']);
const expectedResult = 'result';
const controller = new AbortController();
const p = nodeTimersPromises.setTimeout(2000, expectedResult, {
ref: true,
signal: controller.signal
});
t.mock.timers.tick(1000);
t.mock.timers.tick(500);
t.mock.timers.tick(500);
t.mock.timers.tick(500);
const result = await p;
assert.strictEqual(result, expectedResult);
});
it('should abort operation if timers/promises/setTimeout received an aborted signal', async (t) => {
t.mock.timers.enable(['setTimeout']);
const expectedResult = 'result';
const controller = new AbortController();
const p = nodeTimersPromises.setTimeout(2000, expectedResult, {
ref: true,
signal: controller.signal
});
t.mock.timers.tick(1000);
controller.abort();
t.mock.timers.tick(500);
t.mock.timers.tick(500);
t.mock.timers.tick(500);
await assert.rejects(() => p, {
name: 'AbortError',
});
});
it('should abort operation even if the .tick wasn\'t called', async (t) => {
t.mock.timers.enable(['setTimeout']);
const expectedResult = 'result';
const controller = new AbortController();
const p = nodeTimersPromises.setTimeout(2000, expectedResult, {
ref: true,
signal: controller.signal
});
controller.abort();
await assert.rejects(() => p, {
name: 'AbortError',
});
});
it('should abort operation when .abort is called before calling setInterval', async (t) => {
t.mock.timers.enable(['setTimeout']);
const expectedResult = 'result';
const controller = new AbortController();
controller.abort();
const p = nodeTimersPromises.setTimeout(2000, expectedResult, {
ref: true,
signal: controller.signal
});
await assert.rejects(() => p, {
name: 'AbortError',
});
});
it('should reject given an an invalid signal instance', async (t) => {
t.mock.timers.enable(['setTimeout']);
const expectedResult = 'result';
const p = nodeTimersPromises.setTimeout(2000, expectedResult, {
ref: true,
signal: {}
});
await assert.rejects(() => p, {
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE'
});
});
});
describe('setInterval Suite', () => {
it('should tick three times using fake setInterval', async (t) => {
t.mock.timers.enable(['setInterval']);
const interval = 100;
const intervalIterator = nodeTimersPromises.setInterval(interval, Date.now());
const first = intervalIterator.next();
const second = intervalIterator.next();
const third = intervalIterator.next();
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
const results = await Promise.all([
first,
second,
third,
]);
const finished = await intervalIterator.return();
assert.deepStrictEqual(finished, { done: true, value: undefined });
results.forEach((result) => {
assert.strictEqual(typeof result.value, 'number');
assert.strictEqual(result.done, false);
});
});
it('should tick five times testing a real use case', async (t) => {
t.mock.timers.enable(['setInterval']);
const expectedIterations = 5;
const interval = 1000;
const startedAt = Date.now();
async function run() {
const times = [];
for await (const time of nodeTimersPromises.setInterval(interval, startedAt)) {
times.push(time);
if (times.length === expectedIterations) break;
}
return times;
}
const r = run();
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
const timeResults = await r;
assert.strictEqual(timeResults.length, expectedIterations);
for (let it = 1; it < expectedIterations; it++) {
assert.strictEqual(timeResults[it - 1], startedAt + (interval * it));
}
});
it('should abort operation given an abort controller signal', async (t) => {
t.mock.timers.enable(['setInterval']);
const interval = 100;
const abortController = new AbortController();
const intervalIterator = nodeTimersPromises.setInterval(interval, Date.now(), {
signal: abortController.signal
});
const first = intervalIterator.next();
const second = intervalIterator.next();
t.mock.timers.tick(interval);
abortController.abort();
t.mock.timers.tick(interval);
const firstResult = await first;
// Interval * 2 because value can be a little bit greater than interval
assert.ok(firstResult.value < Date.now() + interval * 2);
assert.strictEqual(firstResult.done, false);
await assert.rejects(() => second, {
name: 'AbortError',
});
});
it('should abort operation when .abort is called before calling setInterval', async (t) => {
t.mock.timers.enable(['setInterval']);
const interval = 100;
const abortController = new AbortController();
abortController.abort();
const intervalIterator = nodeTimersPromises.setInterval(interval, Date.now(), {
signal: abortController.signal
});
const first = intervalIterator.next();
t.mock.timers.tick(interval);
await assert.rejects(() => first, {
name: 'AbortError',
});
});
it('should abort operation given an abort controller signal on a real use case', async (t) => {
t.mock.timers.enable(['setInterval']);
const controller = new AbortController();
const signal = controller.signal;
const interval = 200;
const expectedIterations = 2;
const startedAt = Date.now();
const timeResults = [];
async function run() {
const it = nodeTimersPromises.setInterval(interval, startedAt, { signal });
for await (const time of it) {
timeResults.push(time);
if (timeResults.length === 5) break;
}
}
const r = run();
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
controller.abort();
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
t.mock.timers.tick(interval);
await assert.rejects(() => r, {
name: 'AbortError',
});
assert.strictEqual(timeResults.length, expectedIterations);
for (let it = 1; it < expectedIterations; it++) {
assert.strictEqual(timeResults[it - 1], startedAt + (interval * it));
}
});
});
});
});