2012-01-10 11 views
49

ジャスミンの使用を開始したばかりですので、初心者の質問はお許しください。toHaveBeenCalledWithを使用する場合、オブジェクトタイプをテストすることは可能ですか?JasmineのtoHaveBeenCalledWithメソッドでのオブジェクトタイプの使用

expect(object.method).toHaveBeenCalledWith(instanceof String); 

私はこれを知りましたが、引数ではなく戻り値をチェックしています。

expect(k instanceof namespace.Klass).toBeTruthy(); 

答えて

43

toHaveBeenCalledWithは、スパイの方法です。だから、docsで説明したようにあなたが唯一のスパイでそれらを呼び出すことができます。私は読みやすさのために、最適であることを手で離れて引数を取る見つけるよう

// your class to test 
var Klass = function() { 
}; 

Klass.prototype.method = function (arg) { 
    return arg; 
}; 


//the test 
describe("spy behavior", function() { 

    it('should spy on an instance method of a Klass', function() { 
    // create a new instance 
    var obj = new Klass(); 
    //spy on the method 
    spyOn(obj, 'method'); 
    //call the method with some arguments 
    obj.method('foo argument'); 
    //test the method was called with the arguments 
    expect(obj.method).toHaveBeenCalledWith('foo argument'); 
    //test that the instance of the last called argument is string 
    expect(obj.method.mostRecentCall.args[0] instanceof String).toBeTruthy(); 
    }); 

}); 
+1

アンドレアス、あなたは '.toBeTruthy()'を追加何らかの理由があるのでしょうか?それは不要だと思われます。 – gwg

+1

マッチャーなしの@gwg 'expect(foo)'はノーオペレーションです。 'toBeTruthy()'コールがなければ何もしません。証明についてはhttp://jsfiddle.net/2doafezv/2/を参照してください。 –

+4

これは古くなっています。 'obj.method.mostRecentCall'はJasmine 2.0の[obj.method.calls.mostRecent()'](http://jasmine.github.io/2.0/introduction.html#section-Other_tracking_properties)になる必要があります。また、 'jasmine.any()'を使用すると、他の答えに記載されているように、より明確でより綺麗です。最後に、この回答には少し時間がかかります。基本的にあなたが 'expect(obj.method.mostRecentCall.args [0] instanceof String).toBeTruthy();'のように書いたものは、あなた自身を説明するのに本当に必要なものではありません。 –

84

を私は、jasmine.any()を使用して、でもクーラーメカニズムを発見しました。 CoffeeScriptので

obj = {} 
obj.method = (arg1, arg2) -> 

describe "callback", -> 

    it "should be called with 'world' as second argument", -> 
    spyOn(obj, 'method') 
    obj.method('hello', 'world') 
    expect(obj.method).toHaveBeenCalledWith(jasmine.any(String), 'world') 
+16

jasmine.any(ファンクション)も便利です –

+1

参照で内部でも動作することに気付きました。たとえば: 'expect(obj.method).toHaveBeenCalledWith({done:jasmine.any(Function)})'です。非常に便利。 – fncomp

+1

これは正解です。 – Cam

関連する問題