2013-02-24 17 views
6

Qual è il modo migliore per testare con Jasmine che è stato chiamato un metodo ereditato?Jasmine + test è stato chiamato un metodo ereditato

Sono interessato solo a verificare se è stato chiamato o meno poiché sono stati impostati test di unità per la classe base.

esempio è:

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

voglio provare che methodOne ereditato di ObjectTwo è stato chiamato.

Grazie in anticipo.

risposta

3

Per fare ciò è possibile spiare il metodo nel prototipo di ObjectOne.

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

L'unica avvertenza di questo metodo è che non si controlla se è stato chiamato methodOne sull'oggetto obj. Se è necessario assicurarsi che è stato chiamato obj oggetto, si può fare questo:

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

Non sarebbe lasciare che la spia sul ObjectOne.prototype.methodOne dopo il test in esecuzione? Sono preoccupato che potrebbe causare problemi per altri test che utilizzano questo metodo. Soprattutto per il secondo esempio con .eCallFake() – challet

+0

@challet Questo non dovrebbe essere un problema. Tutte le spie vengono cancellate dopo ogni test. – HoLyVieR

Problemi correlati