2013-02-24 16 views
6

いただきました最善の方法と呼ばれてきましたか?ジャスミン+のテストでは、継承されたメソッドは継承されたメソッドが呼び出されていることをジャスミンをテストするために

私は、基本クラス用に設定ユニットテストを持っているとして、それが呼び出されているかどうかをテスト中だけで興味を持っています。

例は次のとおりです。私はObjectTwoの継承methodOneが呼び出されたことをテストしたい

YUI().use('node', function (Y) { 


    function ObjectOne() { 

    } 

    ObjectOne.prototype.methodOne = function() { 
     console.log("parent method"); 
    } 


    function ObjectTwo() { 
     ObjectTwo.superclass.constructor.apply(this, arguments); 
    } 

    Y.extend(ObjectTwo, ObjectOne); 

    ObjectTwo.prototype.methodOne = function() { 
     console.log("child method"); 

     ObjectTwo.superclass.methodOne.apply(this, arguments); 
    } 
}) 

ありがとうございます。

答えて

3

これを行うには、プロトタイプObjectOneのメソッドを偵察することができます。

spyOn(ObjectOne.prototype, "methodOne").andCallThrough(); 
obj.methodOne(); 
expect(ObjectOne.prototype.methodOne).toHaveBeenCalled(); 

この方法の唯一の注意点はmethodOneobjオブジェクトで呼び出された場合、それはチェックしないであろうということです。あなたはそれがobjオブジェクトで呼び出されたことを確認する必要がある場合は、これを行うことができます:テストが実行された後

var obj = new ObjectTwo(); 
var callCount = 0; 

// We add a spy to check the "this" value of the call. // 
// This is the only way to know if it was called on "obj" // 
spyOn(ObjectOne.prototype, "methodOne").andCallFake(function() { 
    if (this == obj) 
     callCount++; 

    // We call the function we are spying once we are done // 
    ObjectOne.prototype.methodOne.originalValue.apply(this, arguments); 
}); 

// This will increment the callCount. // 
obj.methodOne(); 
expect(callCount).toBe(1);  

// This won't increment the callCount since "this" will be equal to "obj2". // 
var obj2 = new ObjectTwo(); 
obj2.methodOne(); 
expect(callCount).toBe(1); 
+0

はそれがObjectOne.prototype.methodOneにスパイをさせないでしょうか?私は、この方法を使って他のテストで問題を引き起こす可能性があることを心配しています。特に.andCallFake()の2番目の例の場合 – challet

+0

@challetこれは問題ではありません。すべてのスパイは、各テストの後にクリアされます。 – HoLyVieR

関連する問題