Chai: Chai fails when testing an Error

Created on 14 Nov 2013  路  2Comments  路  Source: chaijs/chai

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 :

Chai 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 ?

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,

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);

All 2 comments

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~

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jockster picture jockster  路  4Comments

basherr picture basherr  路  4Comments

JuHwon picture JuHwon  路  5Comments

andipavllo picture andipavllo  路  3Comments

danthegoodman picture danthegoodman  路  3Comments