Skip to content

test_runner: clearTimeout() of a timer from a previous test's mock removes a timer of the current test #67593

Open

Description

@yufei-pan

Version

v26.13.1

Platform

Linux x64

Subsystem

test_runner (mock timers)

What steps will reproduce the bug?

// stale-clear.test.mjs — run with: node --test stale-clear.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';

let stale;
test('first test leaves a timer behind', (t) => {
  t.mock.timers.enable({ apis: ['setTimeout'] });
  stale = setTimeout(() => {}, 1000);
});

test("a timer of the second test fires after the first test's timer is cleared", (t) => {
  t.mock.timers.enable({ apis: ['setTimeout'] });
  let fired = false;
  setTimeout(() => { fired = true; }, 10);
  clearTimeout(stale); // a timer object from the previous test's mock
  t.mock.timers.runAll();
  assert.equal(fired, true);
});

How often does it reproduce? Is there a required condition?

Every run. The condition: a timer object made under one test's mock timers is cleared while a later test's mock timers are enabled.

What is the expected behavior? Why is that the expected behavior?

The second test passes: clearing a timer that is not in the current mock's queue should change nothing, as clearTimeout() of an unknown or already-fired timer does with the real timers.

What do you see instead?

AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

false !== true

The second test's own timer never fires, not even with runAll(). Removing the clearTimeout(stale) line makes the test pass.

Additional information

MockTimers' #clearTimer (lib/internal/test_runner/mock/mock_timers.js) removes by the timer's stored position without checking that the timer belongs to the current queue:

#clearTimer(timer) {
  if (timer?.priorityQueuePosition !== undefined) {
    this.#executionQueue.removeAt(timer.priorityQueuePosition);

So a stale timer's position removes whatever sits at that position in the new test's queue. This looks like the same family as #50365.

Tested on v26.13.1 only. We hit it in a real suite, where the stale clear most likely comes from the previous test's fetch cleaning up its connection after the next test has enabled its mock (not traced); we work around it by waiting 100 ms after closing the previous test's server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    test_runnerIssues and PRs related to the test runner subsystem.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions