【发布时间】: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