mochajs / mocha

☕️ simple, flexible, fun javascript test framework for node.js & the browser
https://mochajs.org
MIT License
22.57k stars 3.01k forks source link

🚀 Feature: Add a global variable in tests indicating the test runner name and version #5084

Open JoshuaKGoldberg opened 8 months ago

JoshuaKGoldberg commented 8 months ago

Feature Request Checklist

Overview

Mocha right now adds standard test hooks to globalThis: after, describe, it, and so on. But there's nothing indicating that it's specifically Mocha being run, and not some other test framework. Would it be reasonable to add some variable like mocha to the global scope?

With this global variable, testing utilities would be able to statically determine the test framework (Mocha) without being explicitly told it in their configuration. This can be useful for utilities that hook into framework-specific APIs.

Suggested Solution

Object.defineProperty(globalThis, "mocha", {
  get: () => ({
    name: "mocha",
    version: "12.34.56"
  }),
});

Alternatives

A process.env would work on the CLI / in Node.js, but not in all browser environments.

Adding some string to a pre-existing global like after might work too, but seems hacky. Right now after.toString() comes out to "function (name, fn) {\n suites[0].afterAll(name, fn);\n }".

Additional Info

See https://github.com/JoshuaKGoldberg/console-fail-test/issues/10: https://github.com/JoshuaKGoldberg/console-fail-test is a utility that runs during tests and uses the test framework's APIs to call testing hooks. It can sort of dynamically detect Mocha, but the implementation is brittle.

CheadleCheadle commented 7 months ago

Hey @JoshuaKGoldberg, I've submitted a pull request for this. Any feedback is much appreciated!

JoshuaKGoldberg commented 7 months ago

Ah, thanks @CheadleCheadle - but this issue hasn't been marked as accepted 😦. We generally only accept feature-adding PRs for issues marked as status: accepting prs. I filed this just a feature request, and am waiting the other maintainers to triage it.

We've been talking a bit on having a separate label to indicate "this is still in triage" for issues. I filed https://github.com/mochajs/mocha/issues/5092 to make it. Sorry that the docs aren't super clear on this yet!

CheadleCheadle commented 7 months ago

Thanks @JoshuaKGoldberg for the clarification on the PR requirements. We'll put a pin in this one for now!