Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test error type in chai [duplicate]

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 :

enter image description here

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 ?

like image 748
Simon Avatar asked Nov 13 '13 16:11

Simon


1 Answers

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 );
like image 50
Miroslav Bajtoš Avatar answered Sep 20 '22 05:09

Miroslav Bajtoš