【发布时间】:2014-05-07 17:46:46
【问题描述】:
在使用 mocha 和 supertest 对我的 node.js 应用程序(基本上是一个 REST 后端)进行单元测试时,我只需要屏幕上的特定于测试的消息,但标准输出中也充满了应用程序日志消息。
我开始单元测试:
mocha -R spec .
... 并得到这个输出(这是它不应该的):
[App] Listening on port 3000 ...
[App] Starting app, hooray!
Project API
GET /projects
[App] entering "projects" module ...
√ should return an array of projects (317ms)
我用 [App] 标记了应用程序日志消息。我真正想要的是单元测试的输出:
Project API
GET /projects
√ should return an array of projects (317ms)
如何抑制应用程序的console.log/warn/error 输出,其中穿插着Mocha 的报告器输出?
解决方案:
按照 dankohn 的方法,我最终得到了这样的结果,这解决了我的问题(使用 winston 进行日志记录):
(在节点的“主”服务器文件 server.js 中:)
if (process.env.NODE_ENV !== 'test') {
logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'foo.log' })
]
});
} else {
// while testing, log only to file, leaving stdout free for unit test status messages
logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({ filename: 'foo.log' })
]
});
}
...并设置环境变量,每个单元测试文件都以:
process.env.NODE_ENV = 'test';
【问题讨论】:
-
嗨,我遇到了一些问题,我使用了类似的方法来修复它,但我仍然在控制台中遇到猫鼬错误。你知道怎么处理吗?
标签: node.js unit-testing mocha.js