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: nodejs#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 Ceres6 committed Aug 14, 2023
1 parent 4b340f5 commit 7e87b0d
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
Original file line number Diff line number Diff line change
Expand Up @@ -1580,6 +1580,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
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const {
FunctionPrototypeBind,
Promise,
SymbolAsyncIterator,
SymbolDispose,
globalThis,
} = primordials;
const {
Expand Down Expand Up @@ -316,6 +317,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
Original file line number Diff line number Diff line change
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 7e87b0d

Please sign in to comment.