Jest: Add logger to print test results in Loki friendly format (#59672)

This commit is contained in:
Ivan Ortega Alba 2022-12-27 12:06:06 +01:00 committed by GitHub
parent 591c86e31d
commit 0d65063d0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 85 additions and 0 deletions

View File

@ -29,4 +29,6 @@ module.exports = {
'\\.css': '<rootDir>/public/test/mocks/style.ts',
'monaco-editor/esm/vs/editor/editor.api': '<rootDir>/public/test/mocks/monaco.ts',
},
// Log the test results with dynamic Loki tags. Drone CI only
reporters: ['default', ['<rootDir>/public/test/log-reporter.js', { enable: process.env.DRONE === 'true' }]],
};

View File

@ -0,0 +1,83 @@
class LogReporter {
constructor(globalConfig, reporterOptions, reporterContext) {
this._globalConfig = globalConfig;
this._options = reporterOptions;
this._context = reporterContext;
}
onRunComplete(testContexts, results) {
if (!this._options.enable) {
return;
}
this.logStats(results);
this.logTestFailures(results);
}
logTestFailures(results) {
results.testResults.forEach(printTestFailures);
}
logStats(results) {
const stats = {
suites: results.numTotalTestSuites,
tests: results.numTotalTests,
passes: results.numPassedTests,
pending: results.numPendingTests,
failures: results.numFailedTests,
duration: Date.now() - results.startTime,
};
// JestStats suites=1 tests=94 passes=93 pending=0 failures=1 duration=3973
console.log(`JestStats ${objToLogAttributes(stats)}`);
}
}
function printTestFailures(result) {
if (result.status === 'pending') {
return;
}
if (result.numFailingTests > 0) {
const testInfo = {
file: result.testFilePath,
failures: result.numFailingTests,
duration: result.perfStats.end - result.perfStats.start,
errorMessage: result.failureMessage,
};
// JestFailure file=<...>/public/app/features/dashboard/state/DashboardMigrator.test.ts
// failures=1 duration=3251 errorMessage="formatted error message"
console.log(`JestFailure ${objToLogAttributes(testInfo)}`);
}
}
/**
* Stringify object to be log friendly
* @param {Object} obj
* @returns {String}
*/
function objToLogAttributes(obj) {
return Object.entries(obj)
.map(([key, value]) => `${key}=${formatValue(value)}`)
.join(' ');
}
/**
* Escape double quotes
* @param {String} str
* @returns
*/
function escapeQuotes(str) {
return String(str).replaceAll('"', '\\"');
}
/**
* Wrap the value within double quote if needed
* @param {*} value
* @returns
*/
function formatValue(value) {
const hasWhiteSpaces = /\s/g.test(value);
return hasWhiteSpaces ? `"${escapeQuotes(value)}"` : value;
}
module.exports = CustomReporter;