I am trying to test that my constructor will throw an error using the Teaspoon gem for Rails, with ChaiJS as my assertion library.
When I run the following 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');
});
I get this output:
Failures:
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')')
The constructor is throwing the error, but I think I am not writing the test properly.
When I try running expect(badConstructor())
then I get the output:
Failures:
1) Seat does not create the seat if x < 0
Failure/Error: Invalid location
Had the same problem. Wrap your constructor with a function:
var fcn = function(){new badConstructor()};
expect(fcn).to.throw(Error, 'Invalid location');
For test a throw message error inside a constructor, with mocha and chai you can write this test (with ES6 syntax):
'use strict';
// ES6 class definition
class A {
constructor(msg) {
if(!msg) throw new Error('Give me the message');
this.message = msg;
}
}
// test.js
describe('A constructor', function() {
it('Should throw an error with "Give me the message" text if msg is null', function() {
(() => new A()).should.throw(Error, /Give me the message/);
});
});
See this Pen for check live working of above code zJppaj by Diego A. Zapata Häntsch (@diegoazh) on CodePen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With