在柴中测试错误类型

Sim*_*mon 7 javascript testing unit-testing chai

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

expect ( place.updateAddress ( [] ) ).to.throw ( TypeError );
Run Code Online (Sandbox Code Playgroud)

这是方法:

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;
};
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

    try {
        place.updateAddress ( [] );
    } catch ( err ) {
        expect ( err ).to.be.an.instanceof ( TypeError );
    }
Run Code Online (Sandbox Code Playgroud)

但是我更喜欢try... catch在我的测试中避免chai使用像内置方法那样的语句throw.

有什么想法/建议吗?

Mir*_*toš 9

您需要将函数传递给chai,但是您的代码正在传递调用函数的结果.

此代码应该可以解决您的问题:

expect (function() { place.updateAddress ( [] ); }).to.throw ( TypeError );
Run Code Online (Sandbox Code Playgroud)