2015-04-22 19 views
11

Próbuję dowiedzieć się czegoś o Sinonie i chcę szpiegować na console.log. Kod jest prosty:Spy na konsolę Sinon. Niezarejestrowana rozmowa

function logToConsole() { 
    console.log('Hello World'); 
} 

exports.logToConsole = logToConsole; 

Ale jeśli chcę go przetestować, to nie działa, ponieważ wywołanie console.log nie jest zarejestrowany wewnątrz systemu, w ramach testu:

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

Jednak gdybym wykonać console.log wewnątrz samego testu, to jest zrobione i przekazuje:

it('should spy on console.log', function() { 
    sinon.spy(console, 'log'); 

    sut.logToConsole(); 
    console.log('Test'); 

    expect(console.log).to.have.been.called; 
}); 

co ciekawe, to nie wydaje się, aby móc szpiegować wewnętrznej-wywołań funkcji w ogóle. Czy nie jest to celem biblioteki szpiegowskiej?

np.

function a() {}; 

function b() { 
    a(); 
} 

Odpowiedz

14

Wygląda na to, że nie jesteśmy rzeczywiście przy sinon-chai kod piszesz brakuje tej linii:

chai.use(sinonChai); 

EDIT: tutaj jest kod I przetestowane:

// 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() { 
}; 
+0

Niestety zapomniałem napisać to na moje pytanie, ale to nic nie zmienia. –

+1

@ninive Dodałem bardziej złożony przykład, który działa dla mnie. – robertklep

+0

Spowoduje to wyświetlenie "Hello World" konsoli testowej - jak to ukryć? – maasha