在Jasmine单元测试中,如何强制失败回调来触发失败请求

In a Jasmine unit test, how do I force a failure callback to trigger that would result from a failed request?

本文关键字:失败 回调 请求 何强制 单元测试 Jasmine      更新时间:2023-09-26

假设我有这个方法(下面是外推的函数):

function doSomething(onSuccess, onFailure){
  var that = this;
  that.$save(function(result){
    if (onSuccess) {
      onSuccess(result);
    }
  }, onFailure);
}

我已经成功地测试了onSuccess回调在该情况下是否会触发$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();
});

您需要让它执行第二个(onFailure)回调

spyOn(that, '$save').and.callFake(function(success, fail) {
    fail();
});

我尝试了Phil的答案(这使测试通过),但觉得这实际上可能不是doSomething函数执行方式的真正测试。为了模仿API的失败,我最终使用$httpBackend并强制执行404响应,这样Angular的$save方法仍然执行:

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
  path = ENV.apiEndpoint + '/things/' + thing.id;
  $httpBackend.expect('POST', path).respond(404);
  thing.addNew(successCallback, failureCallback);
  $httpBackend.flush();
  expect(failureCallback).toHaveBeenCalled();
  expect(successCallback).not.toHaveBeenCalled();
});