2017-05-09 9 views
1

特定のインスタンスメソッドが少なくとも1回呼び出されたかどうかをテストしようとしています。 mochaおよびsinonを使用してください。 ABの2つのクラスがあります。 B#renderA#renderと呼ばれます。テストファイルにはBというインスタンスへのアクセスはありません。すべてのメソッド呼び出しでSinonスパイ

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

これは適切なアプローチですか? あなたが

答えて

0

あなたはそのようにそれを行う必要がありますありがとう:

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

}); 

あなたの仮定が正しかったです。スパイをクラスのプロトタイプレベルで追加します。希望がそれを助ける:)

関連する問題