GeezerVison is showing github.com — test: add Symbol.dispose support to mock timers · nodejs/node@67925bb
File tree
Expand file treeCollapse file tree
Open diff view settings
lib/internal/test_runner/mock
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: doc/api/test.md +4Lines changed: 4 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -1587,6 +1587,10 @@ const { mock } = require('node:test'); |
1587 | 1587 | mock.timers.reset(); |
1588 | 1588 | ``` |
1589 | 1589 |
|
| 1590 | +### `timers[Symbol.dispose]()` |
| 1591 | + |
| 1592 | +Calls `timers.reset()`. |
| 1593 | + |
1590 | 1594 | ### `timers.tick(milliseconds)` |
1591 | 1595 |
|
1592 | 1596 | <!-- YAML |
|
Collapse file
Copy file name to clipboardExpand all lines: lib/internal/test_runner/mock/mock_timers.js +5Lines changed: 5 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -12,6 +12,7 @@ const { |
12 | 12 | FunctionPrototypeBind, |
13 | 13 | Promise, |
14 | 14 | SymbolAsyncIterator, |
| 15 | + SymbolDispose, |
15 | 16 | globalThis, |
16 | 17 | } = primordials; |
17 | 18 | const { |
@@ -315,6 +316,10 @@ class MockTimers { |
315 | 316 | this.#toggleEnableTimers(true); |
316 | 317 | } |
317 | 318 |
|
| 319 | + [SymbolDispose]() { |
| 320 | + this.reset(); |
| 321 | + } |
| 322 | + |
318 | 323 | reset() { |
319 | 324 | // Ignore if not enabled |
320 | 325 | if (!this.#isEnabled) return; |
|
Collapse file
Copy file name to clipboardExpand all lines: test/parallel/test-runner-mock-timers.js +15Lines changed: 15 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -61,6 +61,21 @@ describe('Mock Timers Test Suite', () => { |
61 | 61 | assert.strictEqual(fn.mock.callCount(), 0); |
62 | 62 | }); |
63 | 63 |
|
| 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 | + |
64 | 79 | it('should execute in order if timeout is the same', (t) => { |
65 | 80 | t.mock.timers.enable(); |
66 | 81 | const order = []; |
|