☕️ Classic, reliable, trusted test framework for Node.js and the browser
feat: add built-in github-actions reporter (#6088)
Mostafa Nazaria99b8ba1d621
diff --git a/docs/astro.config.ts b/docs/astro.config.tsindex c49bd99e..7a46cd69 100644--- a/docs/astro.config.ts+++ b/docs/astro.config.ts@@ -72,6 +72,7 @@ export default defineConfig({{ label: "About", slug: "reporters/about" },{ label: "Doc", slug: "reporters/doc" },{ label: "Dot", slug: "reporters/dot" },+ { label: "GitHub Actions", slug: "reporters/github-actions" },{ label: "HTML", slug: "reporters/html" },{ label: "JSON Stream", slug: "reporters/json-stream" },{ label: "JSON", slug: "reporters/json" },diff --git a/docs/src/content/docs/reporters/github-actions.mdx b/docs/src/content/docs/reporters/github-actions.mdxnew file mode 100644index 00000000..ea239a1a--- /dev/null+++ b/docs/src/content/docs/reporters/github-actions.mdx@@ -0,0 +1,14 @@+---+description: The GitHub Actions test reporter for Mocha.+title: GitHub Actions+---++Alias: `GithubActions`, `github-actions`++The GitHub Actions reporter behaves like the [Spec](/reporters/spec) reporter, with extra output tailored to [GitHub Actions](https://docs.github.com/actions) workflows.++When a test fails, it emits an [`::error` workflow command](https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message) annotated with the file, line, and column parsed from the error's stack trace, so failures are shown inline on the pull request diff.++When the `GITHUB_STEP_SUMMARY` environment variable is set (as it is on GitHub-hosted runners), it also appends a short passing/pending/failing summary to the [job summary](https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary).++Enable it from the command line with `--reporter github-actions`, or from a [configuration file](/running/configuring).diff --git a/lib/reporters/github-actions.js b/lib/reporters/github-actions.jsnew file mode 100644index 00000000..28c7ab9d--- /dev/null+++ b/lib/reporters/github-actions.js@@ -0,0 +1,150 @@+/**+ * @typedef {import('../runner.cjs')} Runner+ * @typedef {import('../test.js')} Test+ */++/**+ * @module GithubActions+ */+/**+ * Module dependencies.+ */++import fs from "node:fs";+import ms from "ms";+import { Spec } from "./spec.js";+import Runner from "../runner.cjs";++const { constants } = Runner;+var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;+var EVENT_RUN_END = constants.EVENT_RUN_END;++/**+ * Extract file, line, and column from an error stack trace.+ *+ * @private+ * @param {string} [stackTrace] - stack trace string+ * @return {{ file?: string, line?: string, col?: string }}+ */+function extractLocation(stackTrace) {+ if (!stackTrace) {+ return {};+ }+ var matches =+ /^\s*at Context.*\(([^()]+):([0-9]+):([0-9]+)\)/gm.exec(stackTrace) ||+ /^\s*at.*\(([^()]+):([0-9]+):([0-9]+)\)/gm.exec(stackTrace);+ if (matches === null) {+ return {};+ }+ return {+ file: matches[1],+ line: matches[2],+ col: matches[3],+ };+}++/**+ * Escape a value for use in a GitHub Actions workflow command.+ *+ * @private+ * @param {string} value+ * @return {string}+ */+function escapeWorkflowValue(value) {+ return String(value)+ .replace(/%/g, "%25")+ .replace(/\r/g, "%0D")+ .replace(/\n/g, "%0A");+}++/**+ * Escape a property value for use in a GitHub Actions workflow command.+ *+ * @private+ * @param {string} value+ * @return {string}+ */+function escapeWorkflowProperty(value) {+ return String(value)+ .replace(/%/g, "%25")+ .replace(/\r/g, "%0D")+ .replace(/\n/g, "%0A")+ .replace(/:/g, "%3A")+ .replace(/,/g, "%2C");+}++class GithubActions extends Spec {+ static description =+ "like spec, with GitHub Actions error annotations and job summary";++ /**+ * Construct a new GithubActions reporter instance.+ *+ * @description+ * Extend the Spec reporter to add GitHub Actions error annotations and+ * Job Summary output when running in GitHub Actions CI.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Spec+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);++ var ciFailures = [];++ runner.on(EVENT_TEST_FAIL, function (test) {+ ciFailures.push(test);+ });++ runner.once(EVENT_RUN_END, () => {+ if (ciFailures.length > 0) {+ process.stdout.write("::group::Mocha Annotations\n");++ for (var test of ciFailures) {+ var location = extractLocation(test.err && test.err.stack);+ var props = [];+ if (location.file) {+ props.push("file=" + escapeWorkflowProperty(location.file));+ }+ if (location.line) {+ props.push("line=" + escapeWorkflowProperty(location.line));+ }+ if (location.col) {+ props.push("col=" + escapeWorkflowProperty(location.col));+ }++ var message = test.err ? escapeWorkflowValue(test.err.message) : "";+ process.stdout.write(+ "::error " + props.join(",") + "::" + message + "\n",+ );+ }++ process.stdout.write("::endgroup::\n");+ }++ var summaryFile = process.env.GITHUB_STEP_SUMMARY;+ if (summaryFile) {+ var lines = [];+ lines.push(+ ":white_check_mark: " ++ (this.stats.passes || 0) ++ " passing (" ++ ms(this.stats.duration) ++ ")",+ );+ if (this.stats.pending) {+ lines.push(":pause_button: " + this.stats.pending + " pending");+ }+ if (this.stats.failures) {+ lines.push(":x: " + this.stats.failures + " failing");+ }+ fs.appendFileSync(summaryFile, lines.join("\n") + "\n");+ }+ });+ }+}++export { GithubActions };diff --git a/lib/reporters/index.cjs b/lib/reporters/index.cjsindex c813eda7..5a96cf14 100644--- a/lib/reporters/index.cjs+++ b/lib/reporters/index.cjs@@ -32,3 +32,5 @@ const { Landing } = require("./landing.js");exports.Landing = exports.landing = Landing;const { JSONStream } = require("./json-stream.js");exports.JSONStream = exports["json-stream"] = JSONStream;+const { GithubActions } = require("./github-actions.js");+exports.GithubActions = exports["github-actions"] = GithubActions;diff --git a/test/reporters/github-actions.spec.cjs b/test/reporters/github-actions.spec.cjsnew file mode 100644index 00000000..fae5c2a5--- /dev/null+++ b/test/reporters/github-actions.spec.cjs@@ -0,0 +1,217 @@+"use strict";++var sinon = require("sinon");+var events = require("../../").Runner.constants;+var helpers = require("./helpers.cjs");+var reporters = require("../../").reporters;+var createStatsCollector =+ require("../../lib/stats-collector.js").createStatsCollector;++var Base = reporters.Base;+var GithubActions = reporters.GithubActions;+var createMockRunner = helpers.createMockRunner;+var makeRunReporter = helpers.createRunReporterFunction;++var EVENT_TEST_FAIL = events.EVENT_TEST_FAIL;+var EVENT_TEST_PASS = events.EVENT_TEST_PASS;+var EVENT_RUN_END = events.EVENT_RUN_END;++function createFailEndRunner(test, err) {+ var handlers = {};+ var fn = function (event, callback) {+ if (!handlers[event]) {+ handlers[event] = [];+ }+ handlers[event].push(callback);+ };+ var mockRunner = { on: fn, once: fn };+ createStatsCollector(mockRunner);++ Promise.resolve().then(function () {+ (handlers[EVENT_TEST_FAIL] || []).forEach(function (cb) {+ cb(test, err);+ });+ (handlers[EVENT_RUN_END] || []).forEach(function (cb) {+ cb();+ });+ });++ return mockRunner;+}++describe("GitHub Actions reporter", function () {+ var runReporter = makeRunReporter(GithubActions);+ var noop = function () {};++ beforeEach(function () {+ sinon.stub(Base, "useColors").value(false);+ });++ afterEach(function () {+ sinon.restore();+ delete process.env.GITHUB_STEP_SUMMARY;+ });++ it("should be exported as 'github-actions'", function () {+ expect(reporters["github-actions"], "to be", GithubActions);+ });++ it("should have a static description", function () {+ expect(GithubActions.description, "to be a", "string");+ expect(GithubActions.description, "not to be empty");+ });++ describe("event handlers", function () {+ describe("on 'fail' and 'end' events", function () {+ it("should emit ::error annotation for failures", async function () {+ var err = new Error("expected true to be false");+ err.stack =+ "Error: expected true to be false\n at Context.<anonymous> (test/example.js:10:5)";+ var test = {+ title: "failing test",+ err: err,+ };+ var runner = createFailEndRunner(test, err);+ var options = {};+ var { stdout } = await runReporter({ epilogue: noop }, runner, options);+ sinon.restore();++ var output = stdout.join("");+ expect(output, "to contain", "::group::Mocha Annotations");+ expect(output, "to contain", "::error ");+ expect(output, "to contain", "file=test/example.js");+ expect(output, "to contain", "line=10");+ expect(output, "to contain", "col=5");+ expect(output, "to contain", "expected true to be false");+ expect(output, "to contain", "::endgroup::");+ });++ it("should handle errors without stack trace", async function () {+ var err = new Error("some error");+ err.stack = undefined;+ var test = {+ title: "failing test",+ err: err,+ };+ var runner = createFailEndRunner(test, err);+ var options = {};+ var { stdout } = await runReporter({ epilogue: noop }, runner, options);+ sinon.restore();++ var output = stdout.join("");+ expect(output, "to contain", "::error ");+ expect(output, "to contain", "some error");+ });++ it("should handle a stack trace without a parseable location", async function () {+ var err = new Error("kaboom");+ err.stack = "Error: kaboom\n at <anonymous>";+ var test = {+ title: "failing test",+ err: err,+ };+ var runner = createFailEndRunner(test, err);+ var options = {};+ var { stdout } = await runReporter({ epilogue: noop }, runner, options);+ sinon.restore();++ var output = stdout.join("");+ expect(output, "to contain", "::error ");+ expect(output, "to contain", "kaboom");+ expect(output, "not to contain", "file=");+ expect(output, "not to contain", "line=");+ expect(output, "not to contain", "col=");+ });++ it("should not emit annotations if no failures", async function () {+ var test = {+ title: "passing test",+ duration: 1,+ slow: function () {+ return 75;+ },+ };+ var runner = createMockRunner(+ "pass end",+ EVENT_TEST_PASS,+ EVENT_RUN_END,+ null,+ test,+ );+ var options = {};+ var { stdout } = await runReporter({ epilogue: noop }, runner, options);+ sinon.restore();++ var output = stdout.join("");+ expect(output, "not to contain", "::group::");+ expect(output, "not to contain", "::error");+ });+ });++ describe("on 'end' event with GITHUB_STEP_SUMMARY", function () {+ it("should write job summary when env var is set", async function () {+ var fs = require("fs");+ var tmpFile = require("path").join(+ require("os").tmpdir(),+ "mocha-test-summary-" + Date.now() + ".md",+ );+ process.env.GITHUB_STEP_SUMMARY = tmpFile;++ var test = {+ title: "passing test",+ duration: 1,+ slow: function () {+ return 75;+ },+ };+ var runner = createMockRunner(+ "pass end",+ EVENT_TEST_PASS,+ EVENT_RUN_END,+ null,+ test,+ );+ runner.total = 1;+ var options = {};+ await runReporter(+ {+ epilogue: noop,+ stats: { passes: 1, failures: 2, pending: 3, duration: 100 },+ },+ runner,+ options,+ );+ sinon.restore();++ try {+ var content = fs.readFileSync(tmpFile, "utf8");+ expect(content, "to contain", "passing");+ expect(content, "to contain", "pending");+ expect(content, "to contain", "failing");+ } finally {+ fs.rmSync(tmpFile, { force: true });+ }+ });+ });+ });++ describe("escaping", function () {+ it("should escape newlines and percent signs in error messages", async function () {+ var err = new Error("line1\nline2\n100% done");+ err.stack =+ "Error: line1\nline2\n at Context.<anonymous> (test/file.js:1:1)";+ var test = {+ title: "failing test",+ err: err,+ };+ var runner = createFailEndRunner(test, err);+ var options = {};+ var { stdout } = await runReporter({ epilogue: noop }, runner, options);+ sinon.restore();++ var output = stdout.join("");+ expect(output, "to contain", "%0A");+ expect(output, "to contain", "%25");+ });+ });+});