2013-02-24 20 views
6

Kalıtsal bir yöntemin çağrıldığını Jasmine ile test etmenin en iyi yolu nedir?Jasmine + kalıtsal bir yöntemin test edildi

Yalnızca temel sınıf için ayarlanmış birim sınamalarım olup olmadığının denenip test edilmediğini test etmekle ilgileniyorum.

örnektir: Ben ObjectTwo en miras methodOne anılmış test etmek istiyorum

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

.

Şimdiden teşekkürler.

cevap

3

Bunu yapmak için, yöntemi ObjectOne prototipinde bulabilirsiniz.

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

bu yöntemin sadece uyarı methodOneobj nesne üzerinde çağrıldı eğer kontrol etmeyeceği olmasıdır. Test idam edildikten sonra

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

o ObjectOne.prototype.methodOne üzerinde casus izin vermedi: Eğer obj nesne üzerinde çağrıldı emin olmak gerekiyorsa, bunu yapabilirsiniz? Bu yöntemi kullanarak diğer testler için sorun yaratabilir endişe duyuyorum. Özellikle .andCallFake() – challet

+0

@challet ile ikinci örneği için Bu bir sorun olmamalıdır. Her testten sonra tüm casuslar temizlenir. – HoLyVieR