2012-04-19 15 views
9

Ho la seguente funzione che funzionaLe aspettative di errore in Jasmine

file spec
function sum() 
{ 
    var total = 0, 
     num = 0, 
     numArgs = arguments.length; 

    if (numArgs === 0) { 
     throw new Error("Arguments Expected"); 
    } 

    for(var c = 0; c < numArgs; c += 1) { 
     num = arguments[c]; 
     if (typeof(num) !== "number") { 
      throw new Error("Only number are allowed but found", typeof (num)); 
     } 
     total += num; 

    } 

    return total; 

} 


sum(2, "str"); // Error: Only number are allowed but found "string" 

Il gelsomino è la seguente:

describe("First test; example specification", function() { 
    it("should be able to add 1 + 2", function(){ 
     var add = sum(1, 2); 
     expect(add).toEqual(3); 
    }); 
    it("Second Test; should be able to catch the excption 1 +'s'", function(){ 
     var add = sum(1, "asd"); 
     expect(add).toThrow(new Error("Only number are allowed but found", typeof("asd"))); 
    }); 
}); 

Il test pugno grandi opere, per il secondo ho un difetto test.
Come devo gestire l'errore previsto in Jasmine?

+0

per passare argomenti alla funzione in fase di sperimentazione, senza utilizzare un funzione anonima, prova 'Function.bind': http://stackoverflow.com/a/13233194/294855 –

+0

possibile duplicato di [Come scrivere un test che si aspetta che venga gettato un errore] (http://stackoverflow.com/ domande/4144686/how-to-write-a-test-che-aspetta-an-error-a-essere-gettato) –

risposta

16

Come discusso nel this question, il codice non funziona perché si dovrebbe passare un oggetto funzione di aspettarsi piuttosto che il risultato della chiamata fn()

it("should be able to catch the excption 1 +'s'", function(){ 
//  var add = sum(1, "asd"); 
     expect(function() { 
      sum(1, "asd"); 
     }).toThrow(new Error("Only number are allowed but found", typeof ("asd"))); 
    }); 
Problemi correlati