如何检测Node.js中是否正在运行Mocha测试?
我想确保在代码以测试模式运行的情况下,它不会(偶然)访问错误的数据库.检测代码当前是否在测试模式下运行的最佳方法是什么?
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?
正如在注释中已经提到的那样,构建代码以了解测试是一种不好的做法.我什至找不到关于SO的话题,甚至在外面也找不到.
但是,我可以想到一些方法来检测正在测试中的事实.
对我来说,摩卡不会将自己添加到global
范围内,而是添加global.it
.
因此您的支票可能是
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';
我建议确保不要误检测,以添加对您最有可能在node.js测试中使用的global.sinon
和global.chai
的检查.
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.