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?
相关问题
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- google-drive can't get push notifications
- How to reimport module with ES6 import
- Why is `node.js` dying when called from inside pyt
- How to verify laravel passport api token in node /
相关文章
- node连接远程oracle报错
- How can make folder with Firebase Cloud Functions
- @angular-cli install fails with deprecated request
- node.js modify file data stream?
- How to resolve hostname to an ip address in node j
- Transactionally writing files in Node.js
- Log to node console or debug during webpack build
- Get file created date in node
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.
In a small project with no logging infrastructure, I use
to avoid logging expected errors during testing, as they would interfere with test output.
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: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.
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 addsglobal.it
. So your check may beI would suggest to be sure you don't false-detect to add check for
global.sinon
andglobal.chai
which you most likely used in your node.js tests.Easiest option is to just use the
detect-mocha
[NPM package.If you don't want to do that, the relevant code is just
Where
context
is the currentwindow
orglobal
.