Skip to content

Instantly share code, notes, and snippets.

@donocode
Last active February 16, 2021 07:23
Show Gist options
  • Save donocode/f497190ab145fbe7bbcfd817949cf6fa to your computer and use it in GitHub Desktop.
Save donocode/f497190ab145fbe7bbcfd817949cf6fa to your computer and use it in GitHub Desktop.
Output JSON structured logs from cypress for machine readable test logs
{
"reporter": "structured-log.js",
"quiet": true
}
const Mocha = require('mocha');
const {
EVENT_RUN_BEGIN,
EVENT_RUN_END,
EVENT_TEST_FAIL,
EVENT_TEST_PASS,
EVENT_TEST_RETRY,
EVENT_TEST_PENDING,
} = Mocha.Runner.constants;
class StructuredLog {
constructor(runner) {
const stats = runner.stats;
runner.once(EVENT_RUN_BEGIN, function () {
writeEvent({ type: 'run:start', total: runner.total });
});
runner.on(EVENT_TEST_PASS, function (test) {
writeEvent({ type: 'test:pass', ...clean(test) });
});
runner.on(EVENT_TEST_RETRY, function (test) {
writeEvent({ type: 'test:retry', ...clean(test) });
});
runner.on(EVENT_TEST_PENDING, function (test) {
writeEvent({ type: 'test:skipped', ...clean(test) });
});
runner.on(EVENT_TEST_FAIL, function (test) {
writeEvent({ type: 'test:fail', ...clean(test) });
});
runner.once(EVENT_RUN_END, function () {
writeEvent({ type: 'run:end', ...stats });
});
}
}
function writeEvent(event) {
process.stdout.write(JSON.stringify(event) + '\n');
}
function clean(test) {
return {
title: test.title,
fullTitle: typeof test.fullTitle === 'function' ? test.fullTitle() : test.fullTitle,
file: test.invocationDetails && test.invocationDetails.relativeFile,
duration: test.duration,
currentRetry: typeof test.currentRetry === 'function' ? test.currentRetry() : test.currentRetry,
retries: typeof test.retries === 'function' ? test.retries() : test.retries,
speed: test.speed,
error: test.err
? {
message: test.err.message,
stack: test.err.sourceMappedStack || test.err.stack,
}
: undefined,
};
}
module.exports = StructuredLog;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment