I am currently testing my app with chai
. I would like to test an error thrown by one of my method. To do that, I've written this test :
expect ( place.updateAddress ( [] ) ).to.throw ( TypeError );
And here is the method :
Place.prototype.updateAddress = function ( address ) {
var self = this;
if ( ! utils.type.isObject ( address ) ) {
throw new TypeError (
'Expect the parameter to be a JSON Object, ' +
$.type ( address ) + ' provided.'
);
}
for ( var key in address ) if ( address.hasOwnProperty ( key ) ) {
self.attributes.address[key] = address[key];
}
return self;
};
The problem is that chai
fails on the test because it the method throws a... TypeError
. Which should not fail because it is the expected behavior. Here is the statement :
I have bypassed the problem with the following test :
try {
place.updateAddress ( [] );
} catch ( err ) {
expect ( err ).to.be.an.instanceof ( TypeError );
}
But I'd prefer avoiding try... catch
statements in my tests as chai
provides built-in methods like throw
.
Any idea/suggestion ?
You need to pass a function to chai, but your code is passing the result of calling the function instead.
This code should fix your problem:
expect (function() { place.updateAddress ( [] ); }).to.throw ( TypeError );
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