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: #51673
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com>
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
  • Loading branch information
Benricheson101 authored and richardlau committed Mar 25, 2024
1 parent 0761407 commit 9ff0df1
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 9ff0df1

Please sign in to comment.