This commit is contained in:
Morten Olsen
2025-09-09 18:06:45 +02:00
parent ba7aa90434
commit 0ff0b0992b
25 changed files with 3177 additions and 198 deletions

View File

@@ -0,0 +1,50 @@
import { it as vitestIt } from 'vitest';
type TimedTestOptions = {
logTiming?: boolean;
threshold?: number; // Log only if test takes longer than this (in ms)
};
/**
* A wrapper around vitest's `it` function that measures and logs the execution time
* of just the test body (excluding beforeEach/afterEach hooks).
*/
export function itWithTiming(name: string, fn: () => void | Promise<void>, options: TimedTestOptions = {}) {
const { logTiming = true, threshold = 0 } = options;
return vitestIt(name, async () => {
const startTime = performance.now();
try {
await fn();
} finally {
const endTime = performance.now();
const duration = endTime - startTime;
if (logTiming && duration >= threshold) {
console.log(`⏱️ Test "${name}": ${duration.toFixed(2)}ms (body only)`);
}
}
});
}
/**
* Like timedTest, but only logs timing for slow tests (configurable threshold)
*/
export function slowTest(name: string, fn: () => void | Promise<void>, thresholdMs = 100) {
return itWithTiming(name, fn, { logTiming: true, threshold: thresholdMs });
}
/**
* Measures execution time of a specific code block within a test
*/
export async function measureTime<T>(label: string, fn: () => T | Promise<T>): Promise<T> {
const startTime = performance.now();
try {
return await fn();
} finally {
const endTime = performance.now();
const duration = endTime - startTime;
console.log(`⏱️ ${label}: ${duration.toFixed(2)}ms`);
}
}