2013-02-24 2 views
6

Jasmine에서 상속 된 메서드가 호출되었는지 테스트하는 가장 좋은 방법은 무엇입니까?Jasmine + 상속 된 메서드를 테스트했습니다.

기본 클래스에 대해 단위 테스트를 설정 했으므로 호출 여부에 관계없이 테스트하는 데 관심이 있습니다.

예입니다 : 내가 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 객체에서 호출 된 경우는 확인하지 것입니다. 테스트가 실행 된 후

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에 스파이를하지 않을까요 : 당신이 obj 객체에 호출 된 확인해야하는 경우, 당신은이 작업을 수행 할 수 있습니까? 나는이 방법을 사용하는 다른 테스트에서 문제를 일으킬 수 있다고 우려하고 있습니다. 특히 두 번째 예를 들어 .andCallFake() – challet

+0

@challet 이것은 문제가되지 않습니다. 모든 스파이는 각 테스트 후에 삭제됩니다. – HoLyVieR

관련 문제