Skip to content

Commit

Permalink
test_runner: check if timeout was cleared by own callback
Browse files Browse the repository at this point in the history
PR-URL: nodejs#51673
Reviewed-By: Benjamin Gruenbaum <[email protected]>
Reviewed-By: Marco Ippolito <[email protected]>
Reviewed-By: Moshe Atlow <[email protected]>
  • Loading branch information
Benricheson101 authored and rdw-msft committed Mar 20, 2024
1 parent c3f26c5 commit 70fead8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/internal/test_runner/mock/mock_timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -622,8 +622,12 @@ class MockTimers {
if (timer.runAt > this.#now) break;
FunctionPrototypeApply(timer.callback, undefined, timer.args);

this.#executionQueue.shift();
timer.priorityQueuePosition = undefined;
// Check if the timeout was cleared by calling clearTimeout inside its own callback
const afterCallback = this.#executionQueue.peek();
if (afterCallback.id === timer.id) {
this.#executionQueue.shift();
timer.priorityQueuePosition = undefined;
}

if (timer.interval !== undefined) {
timer.runAt += timer.interval;
Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-runner-mock-timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,22 @@ describe('Mock Timers Test Suite', () => {
await nodeTimersPromises.setImmediate(); // let promises settle
assert.strictEqual(f2.mock.callCount(), 1);
});

it('should not affect other timers when clearing timeout inside own callback', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const f = t.mock.fn();

const timer = nodeTimers.setTimeout(() => {
f();
// Clearing the already-expired timeout should do nothing
nodeTimers.clearTimeout(timer);
}, 50);
nodeTimers.setTimeout(f, 50);
nodeTimers.setTimeout(f, 50);

t.mock.timers.runAll();
assert.strictEqual(f.mock.callCount(), 3);
});
});

describe('setInterval Suite', () => {
Expand Down

0 comments on commit 70fead8

Please sign in to comment.