Skip to content

Commit a9756f3

Browse files
benjamingrRafaelGSS
authored andcommitted
test: add Symbol.dispose support to mock timers
PR-URL: #48549 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Moshe Atlow <[email protected]> Reviewed-By: Antoine du Hamel <[email protected]> Reviewed-By: Erick Wendel <[email protected]>
1 parent cc3a056 commit a9756f3

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

doc/api/test.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1601,6 +1601,10 @@ const { mock } = require('node:test');
16011601
mock.timers.reset();
16021602
```
16031603

1604+
### `timers[Symbol.dispose]()`
1605+
1606+
Calls `timers.reset()`.
1607+
16041608
### `timers.tick(milliseconds)`
16051609

16061610
<!-- YAML

lib/internal/test_runner/mock/mock_timers.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const {
1313
FunctionPrototypeBind,
1414
Promise,
1515
SymbolAsyncIterator,
16+
SymbolDispose,
1617
globalThis,
1718
} = primordials;
1819
const {
@@ -316,6 +317,10 @@ class MockTimers {
316317
this.#toggleEnableTimers(true);
317318
}
318319

320+
[SymbolDispose]() {
321+
this.reset();
322+
}
323+
319324
reset() {
320325
// Ignore if not enabled
321326
if (!this.#isEnabled) return;

test/parallel/test-runner-mock-timers.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,21 @@ describe('Mock Timers Test Suite', () => {
6161
assert.strictEqual(fn.mock.callCount(), 0);
6262
});
6363

64+
it('should reset all timers when calling Symbol.dispose', (t) => {
65+
t.mock.timers.enable();
66+
const fn = t.mock.fn();
67+
global.setTimeout(fn, 1000);
68+
// TODO(benjamingr) refactor to `using`
69+
t.mock.timers[Symbol.dispose]();
70+
assert.throws(() => {
71+
t.mock.timers.tick(1000);
72+
}, {
73+
code: 'ERR_INVALID_STATE',
74+
});
75+
76+
assert.strictEqual(fn.mock.callCount(), 0);
77+
});
78+
6479
it('should execute in order if timeout is the same', (t) => {
6580
t.mock.timers.enable();
6681
const order = [];

0 commit comments

Comments
 (0)