I'm trying to learn about Sinon and want to spy on console.log
. The code is simple:
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:
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:
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();
}
It looks like you're not actually using sinon-chai
, the code you post is missing this line:
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() {
};