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 the method throws a... TypeError. Which should not fail because it is the expected behavior in this test. 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 Chai a function that throws an error. Instead you are not passing Chai anything, because the error is thrown before Chai is ever called. That is,
expect ( place.updateAddress ( [] ) ).to.throw ( TypeError );
is, by the rules of JavaScript, equivalent to
var x = place.updateAddress ( [] );
// Never reached because the above line threw an error
expect ( x ).to.throw ( TypeError );
Instead you should pass it a function that throws an error, e.g.
expect(function () {
place.updateAddress([]);
}).to.throw(TypeError);
Awesome! Also resolved my question~
Most helpful comment
You need to pass Chai a function that throws an error. Instead you are not passing Chai anything, because the error is thrown before Chai is ever called. That is,
is, by the rules of JavaScript, equivalent to
Instead you should pass it a function that throws an error, e.g.