2017-05-09 2 views
1

Ich versuche zu testen, ob eine bestimmte Instanz Methode mindestens einmal aufgerufen wurde. Unter Verwendung von mocha und sinon. Es gibt 2 Klassen: A und B. B#render heißt innerhalb A#render. Es gibt keinen Zugriff auf die Instanz B in einer Testdatei.Sinon Spion auf alle Methodenaufrufe

sinon.spy B.prototype, 'render' 
@instanceA.render 
B.prototype.render.called.should.equal true 
B.prototype.render.restore() 

Ist dies ein richtiger Ansatz, um es zu tun? Danke

Antwort

0

Sie tun sollten, es wie folgt aus:

const chai = require('chai'); 
const sinon = require('sinon'); 
const SinonChai = require('sinon-chai'); 

chai.use(SinonChai); 
chai.should(); 

/** 
* Class A 
* @type {B} 
*/ 
class A { 

    constructor(){ 
     this.b = new B(); 
    } 


    render(){ 
    this.b.render(); 
    } 
} 


/** 
* Class B 
* @type {[type]} 
*/ 
class B { 

    constructor(){ 

    } 

    render(){ 
    } 
} 



context('test', function() { 

    beforeEach(() => { 
    if (!this.sandbox) { 
     this.sandbox = sinon.sandbox.create(); 
    } else { 
     this.sandbox.restore(); 
    } 
    }); 

    it('should pass', 
    (done) => { 

     const a = new A(); 

     const spyA = this.sandbox.spy(A.prototype, 'render'); 
     const spyB = this.sandbox.spy(B.prototype, 'render'); 

     a.render(); 

     spyA.should.have.been.called; 
     spyB.should.have.been.called; 

     done(); 
    }); 

}); 

Ihre Annahme richtig war. Sie fügen die Spione auf der Prototypebene der Klasse hinzu. Hoffe es hilft :)

Verwandte Themen