Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions lib/internal/test_runner/mock/mock_timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ const {
validateNumber,
validateStringArray,
} = require('internal/validators');
const { Module } = require('internal/modules/cjs/loader');
const { syncBuiltinESMExports } = Module;

const {
AbortError,
Expand Down Expand Up @@ -440,9 +442,9 @@ class MockTimers {

const eventIt = EventEmitter.on(emitter, 'data');
const timer = this.#createTimer(true,
() => emitter.emit('data'),
interval,
options);
() => emitter.emit('data'),
interval,
options);

try {
// eslint-disable-next-line no-unused-vars
Expand Down Expand Up @@ -628,6 +630,7 @@ class MockTimers {
const target = activate ? options.toFake : options.toReal;
ArrayPrototypeForEach(this.#timersInContext, (timer) => target[timer]());
this.#isEnabled = activate;
syncBuiltinESMExports();
}

/**
Expand Down
45 changes: 45 additions & 0 deletions test/parallel/test-runner-mock-timers-esm.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import '../common/index.mjs';
import { describe, it } from 'node:test';
import { setTimeout } from 'node:timers/promises';
import assert from 'node:assert';

describe('Mock Timers ESM Regression', () => {
it('should work with node:timers/promises and runAll() in ESM', async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout'] });
const startTime = Date.now();
let t1 = 0;

await Promise.all([
(async () => {
await setTimeout(1000);
t1 = Date.now();
})(),
(async () => {
// Wait for the next tick to ensure setTimeout has been called
await new Promise((resolve) => process.nextTick(resolve));
t.mock.timers.runAll();
})(),
]);

assert.strictEqual(t1 - startTime, 1000);
});

it('should work with node:timers/promises and tick() in ESM', async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout'] });
const startTime = Date.now();
let t1 = 0;

await Promise.all([
(async () => {
await setTimeout(500);
t1 = Date.now();
})(),
(async () => {
await new Promise((resolve) => process.nextTick(resolve));
t.mock.timers.tick(500);
})(),
]);

assert.strictEqual(t1 - startTime, 500);
});
});