mercredi 22 avril 2015

Sinon spy on console.log call not registered

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');

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;
});

Aucun commentaire:

Enregistrer un commentaire