【发布时间】:2016-03-15 11:57:12
【问题描述】:
假设我有这个方法(下面是外推的函数):
function doSomething(onSuccess, onFailure){
var that = this;
that.$save(function(result){
if (onSuccess) {
onSuccess(result);
}
}, onFailure);
}
我已经成功测试了 onSuccess 回调会在 that.$save 按预期执行时触发,但我无法找到任何有关如何做到这一点的文档。$save 无法触发 onFailure 回调。
我创建 onFailure 测试的尝试如下:
it ('should trigger the failure callback if necessary', function(){
var successCallback= jasmine.createSpy('successCallback');
var failureCallback= jasmine.createSpy('failureCallback');
// Force $save to fail to trigger failure callback
thing.$save = function(){};
spyOn(thing, '$save').and.throwError('thing.$save error');
thing.addNew(successCallback, failureCallback);
expect(failureCallback).toHaveBeenCalled();
expect(callback.successCallback).not.toHaveBeenCalled();
});
它仍然会尝试调用成功回调,因为我可以根据此错误判断:
Expected spy failureCallback to have been called.
at /Users/pathy-path
Error: Unexpected request: POST http://website.com/things/5654d74a9b8d05030083239f
No more request expected
如果我将 httpBackend 设置为期待 POST(它不应该因为它应该失败?至少这看起来合乎逻辑),测试失败,因为错误的回调执行:Expected spy failureCallback to have been called.
作为参考,我的 onSuccess 测试看起来像这样(有些简化):
it ('should trigger the success callback', function(){
var successCallback = jasmine.createSpy('successCallback');
path = ENV.apiEndpoint + '/things/' + id;
// if this is triggered we know it would be saved
$httpBackend.expect('POST', path).respond(201);
thing.addNew(successCallback);
$httpBackend.flush();
expect(successCallback).toHaveBeenCalled();
});
【问题讨论】:
标签: javascript unit-testing error-handling jasmine throw