Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript chai中的测试错误类型_Javascript_Unit Testing_Testing_Chai - Fatal编程技术网

Javascript chai中的测试错误类型

Javascript chai中的测试错误类型,javascript,unit-testing,testing,chai,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 ) ) {

我目前正在使用
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
在测试中失败,因为该方法会抛出一个<代码>类型错误。这不应该失败,因为这是预期的行为。声明如下:

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

    try {
        place.updateAddress ( [] );
    } catch ( err ) {
        expect ( err ).to.be.an.instanceof ( TypeError );
    }
但我更喜欢避免
尝试。。。在我的测试中,catch
语句作为
chai
提供了类似
throw
的内置方法


有什么想法/建议吗?

您需要将函数传递给chai,但您的代码将传递调用该函数的结果

此代码将修复您的问题:

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