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