12

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 ?

Simon
  • 1,679
  • 4
  • 21
  • 37

1 Answers1

11

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 );
Miroslav Bajtoš
  • 10,667
  • 1
  • 41
  • 99