From 27ef75790d0215481e328a5e7ec88f510af9e510 Mon Sep 17 00:00:00 2001 From: sudoeren Date: Thu, 19 Nov 2026 18:33:35 +0300 Subject: [PATCH] test_runner: forget queue position of reset mock timers `MockTimers#reset()` emptied the execution queue but left `priorityQueuePosition` set on the removed timers. Clearing such a stale timer later, for example from a previous test after the next test enabled its own mock timers, removed whichever timer sat at that position in the new queue, so that timer never fired. Fixes: https://github.com/nodejs/node/issues/67593 Signed-off-by: sudoeren --- lib/internal/test_runner/mock/mock_timers.js | 8 ++++-- test/parallel/test-runner-mock-timers.js | 30 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) 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', () => {