2016-02-03 14 views
9

Sto usando MeteorJS con angolare e voglio testare il controller. Il mio controller usa $ reactive (this) .attach ($ scope). Devo controllare, se è stato chiamato questo metodo.Jasmine spySulla funzione e oggetto restituito

creo qualcosa di simile per la spia:

var $reactive = function(ctrl) { 
    return { 
     attach:function(scope) {} 
    } 
}; 

così posso chiamarlo così:

$reactive('aaa').attach('bbb'); 

Come posso farlo nei test?

spyOn($reactive, 'attach'); 

Non funziona. Ho ottenuto Errore: il metodo attach() non esiste

E come verificare se è stato chiamato? Questa è una buona chiamata?

expect($reactive).toHaveBeenCalledWith(controller); 

E come verificare che la funzione attach sia stata chiamata con args (scope)?

+0

Sembra che '$ reactive' restituisce un oggetto che contiene il metodo attach, giusto? E tu vuoi testare questo metodo 'attach' per essere stato chiamato. – Raulucco

+0

@Raulucco Esattamente – psalkowski

risposta

4

È necessario prendere in giro il componente $reactive. Sostituirlo con una spia che restituisce uno spyObj nell'ambito del test. Quindi attivare ciò che rende mai il metodo $reactive da eseguire e testare.

var reactiveResult = jasmine.createSpyObj('reactiveResult', ['attach']); 
var $reactive = jasmine.createSpy('$reactive').and.returnValue(reactiveResult); 
var controller = {}; 
    beforeEach(function() { 
     module(function ($provide) { 
     $provide.factory('$reactive', $reactive); 
     }); 
     module('yourAppModule'); 
    }); 

it('Should call attach', function() { 
    $reactive(controller).attach(); 
    expect($reactive).toHaveBeenCalledWith(controller); 
    expect(reactiveResult.attach).toHaveBeenCalled(); 
}) ; 

è possibile fornire il $reactive spia al controller dipendenze troppo:

var reactiveResult = jasmine.createSpyObj('reactiveResult', ['attach']); 
var $reactive = jasmine.createSpy('$reactive').and.returnValue(reactiveResult); 
var ctrl; 
    beforeEach(inject(function ($controller) { 
     ctrl = $controller('YourController', {$reactive: $reactive }); 
    })); 

it('Should call attach', function() { 
    //ctrl.triggerThe$reactiveCall 
    expect($reactive).toHaveBeenCalledWith(ctrl); 
    expect(reactiveResult.attach).toHaveBeenCalled(); 
}) ; 
+0

Grazie mille! Ora so qualcosa di più sui test. – psalkowski