【问题标题】:Test error type in chai [duplicate]chai中的测试错误类型[重复]
【发布时间】:2013-11-26 09:36:07
【问题描述】:

我目前正在使用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。这不应该失败,因为这是预期的行为。这是声明:

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

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

但我更愿意在我的测试中避免使用 try... catch 语句,因为 chai 提供了像 throw 这样的内置方法。

有什么想法/建议吗?

【问题讨论】:

    标签: javascript unit-testing testing chai


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      相关资源
      最近更新 更多