如何检测Node.js中是否正在运行Mocha测试? [英] How to detect if a mocha test is running in node.js?

查看:67
本文介绍了如何检测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.sinonglobal.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.

这篇关于如何检测Node.js中是否正在运行Mocha测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆