How to detect if a mocha test is running in node.j

2019-04-05 04:56发布

I want to make sure that in case the code is running in test mode, that it does not (accidentally) access the wrong database. What is the best way to detect if the code is currently running in test mode?

5条回答
Luminary・发光体
2楼-- · 2019-04-05 05:41

I agreed with @Joshua on his answer, he says Inspecting process.argv is a good approach in my experience.

So, I've written a simple detecting mocha code.

const _MOCHA_PATH = new RegExp('(\\\\|/)node_modules\\1mocha\\1bin\\1_mocha$');
var isMochaRunning = process.argv.findIndex(arg => _MOCHA_PATH.test(arg)) > -1;
查看更多
在下西门庆
3楼-- · 2019-04-05 05:49

In a small project with no logging infrastructure, I use

if (process.env.npm_lifecycle_event !== 'test')
  console.error(e);

to avoid logging expected errors during testing, as they would interfere with test output.

查看更多
贼婆χ
4楼-- · 2019-04-05 05:51

Inspecting process.argv is a good approach in my experience.

For instance if I console.log(process.argv) during a test I get the following:

[
  'node',
  '/usr/local/bin/gulp',
  'test',
  '--file',
  'getSSAI.test.unit.js',
  '--bail',
  '--watch'
]

From which you can see that gulp is being used. Using yargs makes interpretting this a whole lot easier.

I strongly agree with Kirill and in general that code shouldn't be aware of the fact that it's being tested (in your case perhaps you could pass in your db binding / connection via a constructor?), for things like logging I can see why you might want to detect this.

查看更多
做自己的国王
5楼-- · 2019-04-05 05:54

As already mentioned in comment it is bad practice to build your code aware of tests. I even can't find mentioned topic on SO and even outside. However, I can think of ways to detect the fact of being launched in test. For me mocha doesn't add itself to global scope, but adds global.it. So your check may be

var isInTest = typeof global.it === 'function';

I would suggest to be sure you don't false-detect to add check for global.sinon and global.chai which you most likely used in your node.js tests.

查看更多
乱世女痞
6楼-- · 2019-04-05 06:02

Easiest option is to just use the detect-mocha [NPM package.

var detectMocha = require('detect-mocha');
if(detectMocha()) {
  // doSomethingFancy
}

If you don't want to do that, the relevant code is just

function isMochaRunning(context) {
  return ['afterEach','after','beforeEach','before','describe','it'].every(function(functionName){
    return context[functionName] instanceof Function;
})

Where context is the current window or global.

查看更多
登录 后发表回答