我正在尝试了解 Sinon 并想监视 console.log
。代码很简单:
function logToConsole() {
console.log('Hello World');
}
exports.logToConsole = logToConsole;
但是如果我想测试它,它不起作用,因为对 console.log
的调用没有在被测系统内部注册:
var chai = require('chai'),
expect = chai.expect,
sinonChai = require('sinon-chai'),
sinon = require('sinon'),
sut = require('../src/logToConsole');
chai.use(sinonChai);
describe('logToConsole', function() {
it('should spy on console.log', function() {
sinon.spy(console, 'log');
sut.logToConsole();
expect(console.log).to.have.been.called;
});
});
但是,如果我在测试本身内部执行 console.log
,它会被捕获并通过:
it('should spy on console.log', function() {
sinon.spy(console, 'log');
sut.logToConsole();
console.log('Test');
expect(console.log).to.have.been.called;
});
有趣的是,它似乎根本无法监视内部函数调用。这不是 spy 图书馆的目的吗?
例如
function a() {};
function b() {
a();
}
最佳答案
看起来你实际上并没有使用 sinon-chai
,你发布的代码缺少这一行:
chai.use(sinonChai);
编辑:这是我测试过的代码:
// test.js
var chai = require('chai'),
expect = chai.expect,
sinonChai = require('sinon-chai'),
sinon = require('sinon'),
sut = require('./log');
chai.use(sinonChai);
describe('logging', function() {
beforeEach(function() {
sinon.spy(console, 'log');
});
afterEach(function() {
console.log.restore();
});
describe('logToConsole', function() {
it('should log to console', function() {
sut.logToConsole();
expect(console.log).to.be.called;
});
});
describe('logToConsole2', function() {
it('should not log to console', function() {
sut.logToConsole2();
expect(console.log).to.not.be.called;
});
});
});
// log.js
module.exports.logToConsole = function() {
console.log('Hello World');
};
module.exports.logToConsole2 = function() {
};
关于javascript - Sinon 监视未注册的 console.log 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802117/