How to detect which test framework is running the code

I wrote a small library to enhance the testing of my web app and now want to abstract it away into a separate open-source project. The library is generic enough that it would be useful not just for myself on other projects but also for others.

The only problem is that it implements a set of custom matchers and some jest-specific logic (this is done as a convenience to make actual test code less verbose). Implementing equivalent logic for other test frameworks should be straight-forward, but I’m struggling to understand how to consistently identify which test framework is running (to select correct assertion logic).

I know jest sets certain environment variables (How to determine if JEST is running the code or not?), but based on the answer the jest-specific variable is not consistently set and NODE_ENV would be set to the same test value by all test frameworks. What’s the cleanest approach for detecting which test framework is executing the test? Thanks

Answer

After looking at all of the environment variables, seeing which ones are consistent and which aren’t, here is a function I put together for determining the launcher/framework:

const path = require('path');
function detectFramework() {
  const launcher = process.env._;
  return path.basename(launcher);
}

This will work regardless of how you nickname your launch script in package.json. Hopefully someone else finds this useful as well.

Leave a Reply

Your email address will not be published. Required fields are marked *