How to detect which test framework is running the code Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to detect which test framework is running the code without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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


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.

We are here to answer your question about How to detect which test framework is running the code - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji