Код: Выделить всё
export async function useTimeout() {
const sleep = () => new Promise((resolve) => setTimeout(resolve, 1000));
let c = 1;
while (true) {
c += 1;
if (c > 5) {
break;
}
// THIS LINE BREAKS THE TEST
// await new Promise((resolve) => {resolve()});
await sleep();
console.log('sleep done!')
}
return c
}
Код: Выделить всё
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { useTimeout } from './useTimeout.js'; // Adjust the import path as necessary
test('useTimeout waits for 5 seconds and logs message', async (t) => {
t.mock.timers.enable(['setTimeout']);
const timeoutFunction = useTimeout();
// Manually advance timers and yield to microtasks for each second
for (let i = 0; i < 5; i++) {
t.mock.timers.tick(1000);
console.log(`Tick ${i + 1}: 1 second passed`);
await Promise.resolve();
}
// Await the result
const result = await timeoutFunction;
assert.strictEqual(result, 6, 'useTimeout should return 6 after 5 iterations');
});
Почему это?
Подробнее здесь: https://stackoverflow.com/questions/796 ... imers-tick