with-performance.ts
This file
Path
test/helpers/with-performance.ts
30 lines · 905 bytes · TypeScript
Last changed by
Fix flaky testsSindre Sorhusbefore adoptionfec6c43
History of this fileTake it
12345678910111213141516171819202122232425262728293031import {performance} from 'node:perf_hooks';import process from 'node:process';import type {ExecutionContext} from 'ava';
type Argument = { expectedDuration: number; t: ExecutionContext; test: () => Promise<void>;};
// We allow the tests to take more time on CI than locally, to reduce flakiness// Node.js 22+ has higher overhead on CI (~400-650ms), so we increase the toleranceconst nodeVersion = Number(process.versions.node.split('.')[0]);const allowedOffset = process.env.CI ? (nodeVersion >= 22 ? 700 : 500) : 400;
export async function withPerformance({ expectedDuration, t, test,}: Argument) { const startTime = performance.now(); await test(); const endTime = performance.now();
const duration = endTime - startTime; t.true( Math.abs(duration - expectedDuration) < allowedOffset, `Duration of ${duration}ms is not close to expected duration ${expectedDuration}ms`, );}