Узел: тестируйте таймеры промывки при использовании t.mock.timers.tick?Javascript

Форум по Javascript
Anonymous
Узел: тестируйте таймеры промывки при использовании t.mock.timers.tick?

Сообщение Anonymous »

У меня есть следующая простая функция: < /p>

Код: Выделить всё

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
}
Я тестирую функцию с помощью узла: тест на узле v22 (то же самое с узлом v24)

Код: Выделить всё

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

Вернуться в «Javascript»