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
.
有什么想法/建议吗?
您需要将函数传递给chai,但是您的代码正在传递调用函数的结果.
此代码应该可以解决您的问题:
expect (function() { place.updateAddress ( [] ); }).to.throw ( TypeError );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3673 次 |
最近记录: |