javascript Sinon 监视 console.log 调用未注册
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29802117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sinon spy on console.log call not registered
提问by robertklep
I'm trying to learn about Sinon and want to spy on console.log
. The code is simple:
我正在尝试了解诗浓并想监视console.log
. 代码很简单:
function logToConsole() {
console.log('Hello World');
}
exports.logToConsole = logToConsole;
But if I want to test it, it doesn't work because the call to console.log
is not registered inside the system under test:
但是如果我想测试它,它不起作用,因为调用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;
});
});
However if I execute console.log
inside the test itself, it is captured and passes:
但是,如果我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;
});
Interestingly, it doesn't seem to be able to spy on inner-function calls at all. Is this not the purpose of a spying library?
有趣的是,它似乎根本无法监视内部函数调用。这不是间谍图书馆的目的吗?
e.g.
例如
function a() {};
function b() {
a();
}
回答by robertklep
It looks like you're not actually using sinon-chai
, the code you post is missing this line:
看起来您实际上并没有使用sinon-chai
,您发布的代码缺少这一行:
chai.use(sinonChai);
EDIT: here is the code I tested with:
编辑:这是我测试的代码:
// 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() {
};