我有什么办法可以监视本尼扬日志,以确保打印出我期望的内容?
MyFile.js
const bunyan = require('bunyan');
const log = bunyan.createLogger({name: 'FailureAuditService'});
class someClass {
someFunct() {
if(x) {
log.warn('something happened');
}
}
}
测试
const service = require(../MyFile);
describe('test something', () => {
it('Will test the bunyan log', res => {
let consoleLog = sinon.spy(log, 'createLogger');
let x = true;
service.someClass(x).then(res => {
let expected = 'something happened';
consoleLog.should.equal(expected);
});
});
})
答案 0 :(得分:3)
是的,使用Jest很简单:
let spyLogWarn = jest.spyOn(require('bunyan').prototype, 'warn')
// ...
expect(spyLogWarn).toHaveBeenCalled()
答案 1 :(得分:1)
我通过以下方法解决了这个问题:
const mockReq = require('mock-require);
...
let infoStub = sinon.stub();
let warnStub = sinon.stub();
logStubs = {
info: infoStub,
warn: warnStub
// any other log methods you wish to use
};
mockReq('bunyan', {
createLogger() {
return logStubs;
}
});
...
然后,我后来使用过mockReq.reRequire()函数来重置我要模拟的服务的缓存。
要声明日志的实际内容:
let infoLog = infoStub.firstCall.args[0];
let warnLog = warnStub.firstCall.args[0];
有了这个,我可以断言它们等于我的期望。
答案 2 :(得分:0)
For Sinon you may write something like:
const bunyan = require('bunyan');
sinon.stub(bunyan.prototype);
// or
sinon.stub(bunyan.prototype, 'fatal');
// or
sinon.stub(bunyan.prototype, 'fatal').callThrough();
And in asserting
sinon.assert.calledOnce(bunyan.prototype.fatal);