javascript - Sinon spy on console.log call not registered -
i'm trying learn sinon , want spy on console.log
. code simple:
function logtoconsole() { console.log('hello world'); } exports.logtoconsole = logtoconsole;
but if want test it, doesn't work because call console.log
not registered inside 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 execute console.log
inside test itself, captured , 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, doesn't seem able spy on inner-function calls @ all. not purpose of spying library?
e.g.
function a() {}; function b() { a(); }
it looks you're not using sinon-chai
, code post missing line:
chai.use(sinonchai);
edit: here code 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 console', function() { sut.logtoconsole(); expect(console.log).to.be.called; }); }); describe('logtoconsole2', function() { it('should not log 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() { };
Comments
Post a Comment