Skip to content

Commit 1683e60

Browse files
authored
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 fe4ac37 commit 1683e60

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
@@ -1580,6 +1580,10 @@ const { mock } = require('node:test');
15801580
mock.timers.reset();
15811581
```
15821582

1583+
### `timers[Symbol.dispose]()`
1584+
1585+
Calls `timers.reset()`.
1586+
15831587
### `timers.tick(milliseconds)`
15841588

15851589
<!-- 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)