Skip to content

Commit

Permalink
test: add Symbol.dispose support to mock timers
Browse files Browse the repository at this point in the history
PR-URL: #48549
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Erick Wendel <erick.workspace@gmail.com>
  • Loading branch information
benjamingr authored and targos committed Nov 26, 2023
1 parent 7f68e14 commit 67925bb
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
4 changes: 4 additions & 0 deletions doc/api/test.md
Expand Up @@ -1587,6 +1587,10 @@ const { mock } = require('node:test');
mock.timers.reset();
```

### `timers[Symbol.dispose]()`

Calls `timers.reset()`.

### `timers.tick(milliseconds)`

<!-- YAML
Expand Down
5 changes: 5 additions & 0 deletions lib/internal/test_runner/mock/mock_timers.js
Expand Up @@ -12,6 +12,7 @@ const {
FunctionPrototypeBind,
Promise,
SymbolAsyncIterator,
SymbolDispose,
globalThis,
} = primordials;
const {
Expand Down Expand Up @@ -315,6 +316,10 @@ class MockTimers {
this.#toggleEnableTimers(true);
}

[SymbolDispose]() {
this.reset();
}

reset() {
// Ignore if not enabled
if (!this.#isEnabled) return;
Expand Down
15 changes: 15 additions & 0 deletions test/parallel/test-runner-mock-timers.js
Expand Up @@ -61,6 +61,21 @@ describe('Mock Timers Test Suite', () => {
assert.strictEqual(fn.mock.callCount(), 0);
});

it('should reset all timers when calling Symbol.dispose', (t) => {
t.mock.timers.enable();
const fn = t.mock.fn();
global.setTimeout(fn, 1000);
// TODO(benjamingr) refactor to `using`
t.mock.timers[Symbol.dispose]();
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 = [];
Expand Down

0 comments on commit 67925bb

Please sign in to comment.