2015-04-22 17 views
11

Sinon hakkında bilgi edinmek ve console.log numaralı telefondan casusluk yapmak istiyorum.Konsol.log'da Sinon casus çağrı kayıtlı değil

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

exports.logToConsole = logToConsole; 

Ama bunu test etmek istiyorsanız console.log çağrısı test edilen sistemin içine kayıtlı olmadığından, bu çalışmaz:: Kod basittir Ancak yürütmek eğer

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

Test kendisi içeride console.log, aynen alınıp geçer:

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

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

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

İlginçtir, hiç çağırır iç işlevine gözetlemek mümkün görünmemektedir. Bu casusluk kütüphanesinin amacı değil mi?

örn.

chai.use(sinonChai); 

EDIT:

aslında sinon-chai kullanmadığınız anlaşılıyor
function a() {}; 

function b() { 
    a(); 
} 

cevap

14

, yayınladığınız kod satırı eksik olduğunu

// 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() { 
}; 
: Burada ben ile test kodu
+0

Sorgumda yazmayı unuttum, ama bir şeyi değiştirmiyor. –

+1

@ninive Benim için çalışan daha ayrıntılı bir örnek ekledim. – robertklep

+0

Bu, 'Merhaba Dünya'yı test konsoluna gönderecek - bunu nasıl gizleyeceksiniz? – maasha

İlgili konular