2012-01-10 3 views
49

방금 ​​Jasmine을 사용하기 시작했습니다. 초보자 질문을 용서하십시오. 그러나 toHaveBeenCalledWith을 사용할 때 객체 유형을 테스트 할 수 있습니까?Jasmine의 toHaveBeenCalledWith 메소드와 함께 객체 유형 사용하기

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

나는 이것을 알 수 있지만 인수가 아닌 반환 값을 확인하고 있습니다.

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

답변

43

toHaveBeenCalledWith은 스파이의 한 방법입니다. docs 설명처럼 그래서 당신은 스파이에 그들을 호출 할 수 있습니다 : 나는 jasmine.any() 사용하여 더 쿨러 메커니즘을 발견했습니다

// 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

, 내가 가독성을위한 차선으로 손으로 떨어져 인수를 복용 찾을한다. 커피 스크립트에서

:

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

관련 문제