2014-11-12 12 views

risposta

67

È possibile utilizzare spy.and.returnValues (come Jasmine 2.4).

ad esempio

describe("A spy, when configured to fake a series of return values", function() { 
 
    beforeEach(function() { 
 
    spyOn(util, "foo").and.returnValues(true, false); 
 
    }); 
 

 
    it("when called multiple times returns the requested values in order", function() { 
 
    expect(util.foo()).toBeTruthy(); 
 
    expect(util.foo()).toBeFalsy(); 
 
    expect(util.foo()).toBeUndefined(); 
 
    }); 
 
});

V'è qualche cosa che si deve stare attenti, c'è un'altra funzione incantesimo simile returnValue senza s, se si utilizza tale, gelsomino non avvisa .

+0

Questa è ora la migliore risposta. – mikhail

+8

+1: questa è una caratteristica eccellente. Una parola di avvertimento, però - fai attenzione a non dimenticare la "s" in ".returnValues" - le due funzioni sono ovviamente diverse, ma passare più argomenti a ".returnValue" non genera un errore. Non voglio ammettere quanto tempo ho perso a causa di quel personaggio. –

+0

@TheDIMMReaper, grazie. Lo dico ora. – Ocean

16

Per le versioni precedenti di Jasmine, è possibile utilizzare spy.andCallFake per Jasmine 1.3 o spy.and.callFake per Jasmine 2.0, e si dovrà tenere traccia dello stato "chiamato", tramite una semplice chiusura, o proprietà dell'oggetto, ecc.

+3

Possiamo estendere questo per più di 2 chiamate in questo modo: var risultati = [true, false , "foo"]; var callCount = 0; spyOn (util, "foo"). And.callFake (function() { restituisce risultati [callCount ++]; }); – Jack

+1

Questo può essere esteso ad una funzione generica come questa: function returnValues ​​() {var args = arguments; var callCount = 0; return function() {return args [callCount ++]; }; } –

0

Se si desidera scrivere una specifica per ogni chiamata è anche possibile utilizzare beforeAll invece di beforeeach:

describe("A spy taking a different value in each spec", function() { 
    beforeAll(function() { 
    spyOn(util, "foo").and.returnValues(true, false); 
    }); 

    it("should be true in the first spec", function() { 
    expect(util.foo()).toBeTruthy(); 
    }); 

    it("should be false in the second", function() { 
    expect(util.foo()).toBeFalsy(); 
    }); 
}); 
+0

I test non devono essere dipendenti l'uno dall'altro. – Ocean

Problemi correlati