Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 671
Michael_Scharf Avatar asked Mar 21 '15 13:03

Michael_Scharf


People also ask

How do I check Mocha version in terminal?

Use npx to solve the error "mocha: command not found", e.g. npx mocha or install the package globally by running npm install -g mocha to be able to use the command without the npx prefix. The fastest way to solve the error is to use the npx command.


2 Answers

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.

like image 21
Joshua Avatar answered Sep 23 '22 15:09

Joshua


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.

like image 108
Kirill Slatin Avatar answered Sep 23 '22 15:09

Kirill Slatin