Files
cgm-remote-monitor/tests/hooks.js
T
bewestandBen West 851d46b99f Add test instrumentation to detect and warn about flaky tests
Introduce timing instrumentation to identify slow tests and setTimeout anti-patterns, refactor helper functions into a shared module, and update documentation and npm scripts.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: a10b5171-2266-431b-a8b1-bbc77898c289
Replit-Commit-Checkpoint-Type: intermediate_checkpoint
Replit-Commit-Event-Id: fdf582ee-3e62-4543-a850-a72060814d7d
Replit-Helium-Checkpoint-Created: true
2026-01-19 13:14:46 -08:00

76 lines
2.2 KiB
JavaScript

'use strict;'
var testHelpers = require('./lib/test-helpers');
var slowTestThreshold = parseInt(process.env.SLOW_TEST_THRESHOLD, 10) || 2000;
var enableTimingWarnings = process.env.ENABLE_TIMING_WARNINGS === 'true';
var restoreSetTimeout = null;
var testTimings = [];
function clearRequireCache () {
Object.keys(require.cache).forEach(function(key) {
delete require.cache[key];
});
}
exports.mochaHooks = {
beforeAll(done) {
if (enableTimingWarnings) {
console.log('[TIMING INSTRUMENTATION] Enabled - will warn on setTimeout anti-patterns');
restoreSetTimeout = testHelpers.enableSetTimeoutWarnings({
warnOnLongDelays: true,
longDelayThreshold: 100
});
}
done();
},
beforeEach(done) {
this.testStartTime = Date.now();
done();
},
afterEach(done) {
if (this.testStartTime) {
var elapsed = Date.now() - this.testStartTime;
var testTitle = this.currentTest ? this.currentTest.fullTitle() : 'unknown';
testTimings.push({
title: testTitle,
duration: elapsed,
slow: elapsed > slowTestThreshold
});
if (elapsed > slowTestThreshold) {
console.warn('[SLOW TEST] "' + testTitle + '" took ' + elapsed + 'ms (threshold: ' + slowTestThreshold + 'ms)');
}
}
clearRequireCache();
done();
},
afterAll(done) {
if (restoreSetTimeout) {
var setTimeoutCallCount = restoreSetTimeout();
console.log('[TIMING INSTRUMENTATION] Disabled - detected ' + setTimeoutCallCount + ' setTimeout calls');
}
if (testTimings.length > 0) {
var slowTests = testTimings.filter(function(t) { return t.slow; });
if (slowTests.length > 0) {
console.log('\n[SLOW TEST SUMMARY] ' + slowTests.length + ' slow test(s) detected:');
slowTests.forEach(function(t, i) {
console.log(' ' + (i + 1) + '. ' + t.title + ' (' + t.duration + 'ms)');
});
}
var totalTime = testTimings.reduce(function(sum, t) { return sum + t.duration; }, 0);
var avgTime = Math.round(totalTime / testTimings.length);
console.log('\n[TIMING STATS] Total: ' + testTimings.length + ' tests, Avg: ' + avgTime + 'ms, Slow: ' + slowTests.length);
}
done();
}
};