在柴中测试错误类型

时间:2013-11-13 16:50:01

标签: javascript unit-testing testing chai

我目前正在使用chai测试我的应用。我想测试一个我的方法抛出的错误。为此,我写了这个测试:

expect ( place.updateAddress ( [] ) ).to.throw ( TypeError );

以下是方法:

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

问题是chai测试失败,因为该方法会抛出... TypeError。哪个不应该失败,因为它是预期的行为。以下是声明:

enter image description here

我已通过以下测试绕过了问题:

    try {
        place.updateAddress ( [] );
    } catch ( err ) {
        expect ( err ).to.be.an.instanceof ( TypeError );
    }

但我希望在我的测试中避免使用try... catch语句,因为chai提供了throw等内置方法。

有任何想法/建议吗?

1 个答案:

答案 0 :(得分:8)

你需要将一个函数传递给chai,但你的代码却传递了调用函数的结果。

此代码应解决您的问题:

expect (function() { place.updateAddress ( [] ); }).to.throw ( TypeError );
相关问题