在单元测试我的 node 时.js应用程序(基本上是一个REST后端)使用mocha和supertest,我只需要屏幕上显示特定于测试的消息,但stdout中也充斥着应用程序日志(log)消息.
我从以下内容开始单元测试:
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]标记了应用程序日志(log)消息.I really want将是单元测试的输出:
Project API
GET /projects
√ should return an array of projects (317ms)
我怎样才能 suppress 控制台.应用程序的日志(log)/警告/错误输出与Mocha的reporter输出交错?
SOLUTION:
按照dankohn的方法,我的结局是这样的,这解决了我的问题(使用winston进行日志(log)记录):
(在 node 的"主"服务器文件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' })
]
});
}
... 要设置env变量,每个单元测试文件都以以下内容开头:
process.env.NODE_ENV = 'test';