2015-05-11 31 views
9

Sto provando a verificare che il mio costruttore lancia un errore usando la gemma Teaspoon per Rails, con ChaiJS come libreria di asserzione.ChaiJS si aspetta che il costruttore lanci l'errore

Quando eseguo il seguente test:

it('does not create the seat if x < 0', function() { 
    var badConstructor = function() { 
     return new Seat({ radius: 10, x: -0.1, y: 0.2, seat_number: 20, table_number: 30}); 
    }; 

    expect(badConstructor).to.throw(Error, 'Invalid location'); 
    }); 

ottengo questo output:

Fallimenti:

1) Seat does not create the seat if x < 0 
    Failure/Error: undefined is not a constructor (evaluating 'expect(badConstructor).to.throw(Error(), 'Invalid location')') 

Il costruttore sta gettando l'errore, ma penso che non sto scrivendo il test correttamente.

Quando provo correre expect(badConstructor()) poi ho ottenere l'output:

Failures: 

    1) Seat does not create the seat if x < 0 
    Failure/Error: Invalid location 
+0

È inteso che sia "expect (badConstructor())'? cioè, è necessario chiamare la funzione. – Andy

+0

L'ho appena provato, inutilmente. Ora ricevo un altro errore - l'ho aggiunto nell'OP. – ThomYorkkke

+0

Quindi sembra che funzioni correttamente poiché "la posizione non valida" fa parte del messaggio di errore. È necessario prenderlo nel test o aggiungere un'istruzione 'try/catch' nella funzione per restituire un errore che è possibile verificare. – Andy

risposta

21

avuto lo stesso problema. Avvolgi il tuo costruttore con una funzione:

var fcn = function(){new badConstructor()}; 
expect(fcn).to.throw(Error, 'Invalid location'); 
+0

Sembra un po 'una soluzione hacky, ma sicuramente fa il lavoro. – Connor

+0

Funziona anche per me. @Connor qualsiasi motivo per cui è "hacky"? – JohnnyQ

+0

@JohnnyQ Voglio dire che, al momento, conoscevo solo uno degli stili di asserzione di Chai. Quasi un anno dopo, però, non sembra affatto hacky. Se potessi, annullerei quel commento! – Connor

Problemi correlati