Skip to content

Commit af5875c

Browse files
Benricheson101targos
authored andcommitted
test_runner: check if timeout was cleared by own callback
PR-URL: #51673 Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com> Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
1 parent 7ceb6d6 commit af5875c

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

lib/internal/test_runner/mock/mock_timers.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -622,8 +622,12 @@ class MockTimers {
622622
if (timer.runAt > this.#now) break;
623623
FunctionPrototypeApply(timer.callback, undefined, timer.args);
624624

625-
this.#executionQueue.shift();
626-
timer.priorityQueuePosition = undefined;
625+
// Check if the timeout was cleared by calling clearTimeout inside its own callback
626+
const afterCallback = this.#executionQueue.peek();
627+
if (afterCallback.id === timer.id) {
628+
this.#executionQueue.shift();
629+
timer.priorityQueuePosition = undefined;
630+
}
627631

628632
if (timer.interval !== undefined) {
629633
timer.runAt += timer.interval;

test/parallel/test-runner-mock-timers.js

+16
Original file line numberDiff line numberDiff line change
@@ -532,6 +532,22 @@ describe('Mock Timers Test Suite', () => {
532532
await nodeTimersPromises.setImmediate(); // let promises settle
533533
assert.strictEqual(f2.mock.callCount(), 1);
534534
});
535+
536+
it('should not affect other timers when clearing timeout inside own callback', (t) => {
537+
t.mock.timers.enable({ apis: ['setTimeout'] });
538+
const f = t.mock.fn();
539+
540+
const timer = nodeTimers.setTimeout(() => {
541+
f();
542+
// Clearing the already-expired timeout should do nothing
543+
nodeTimers.clearTimeout(timer);
544+
}, 50);
545+
nodeTimers.setTimeout(f, 50);
546+
nodeTimers.setTimeout(f, 50);
547+
548+
t.mock.timers.runAll();
549+
assert.strictEqual(f.mock.callCount(), 3);
550+
});
535551
});
536552

537553
describe('setInterval Suite', () => {

0 commit comments

Comments
 (0)