diff --git a/lib/internal/test_runner/mock/mock_timers.js b/lib/internal/test_runner/mock/mock_timers.js index 1e425b606ee5..a42b8859804a 100644 --- a/lib/internal/test_runner/mock/mock_timers.js +++ b/lib/internal/test_runner/mock/mock_timers.js @@ -799,10 +799,12 @@ class MockTimers { this.#timersInContext = []; this.#now = kInitialEpoch; - let timer = this.#executionQueue.peek(); + let timer = this.#executionQueue.shift(); while (timer) { - this.#executionQueue.shift(); - timer = this.#executionQueue.peek(); + // Forget the queue position so that clearing this timer later does + // not remove whatever timer occupies that position afterwards. + timer.priorityQueuePosition = undefined; + timer = this.#executionQueue.shift(); } } diff --git a/test/parallel/test-runner-mock-timers.js b/test/parallel/test-runner-mock-timers.js index 25510fe023d0..c95112a160bd 100644 --- a/test/parallel/test-runner-mock-timers.js +++ b/test/parallel/test-runner-mock-timers.js @@ -338,6 +338,36 @@ describe('Mock Timers Test Suite', () => { nodeTimers.clearTimeout(); nodeTimers.clearTimeout(null); }); + + it('clearing a timer from before a reset does not remove a new timer', (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const stale = globalThis.setTimeout(common.mustNotCall(), 1000); + t.mock.timers.reset(); + + t.mock.timers.enable({ apis: ['setTimeout'] }); + const fn = t.mock.fn(); + globalThis.setTimeout(fn, 10); + globalThis.clearTimeout(stale); + t.mock.timers.runAll(); + + assert.strictEqual(fn.mock.callCount(), 1); + }); + + it('clearing a timer from another MockTimers instance does not remove a timer', (t) => { + const { MockTracker } = require('internal/test_runner/mock/mock'); + const other = new MockTracker(); + other.timers.enable({ apis: ['setTimeout'] }); + const stale = globalThis.setTimeout(common.mustNotCall(), 1000); + other.reset(); + + t.mock.timers.enable({ apis: ['setTimeout'] }); + const fn = t.mock.fn(); + globalThis.setTimeout(fn, 10); + globalThis.clearTimeout(stale); + t.mock.timers.runAll(); + + assert.strictEqual(fn.mock.callCount(), 1); + }); }); describe('setInterval Suite', () => {