【问题标题】:Testing try/catch in Jasmine is not working在 Jasmine 中测试 try/catch 不起作用
【发布时间】:2020-03-24 15:52:55
【问题描述】:

我正在尝试测试 AngularJS 中的这段代码:

var _savePendingChanges = function() {
  try {
    $rootScope.$broadcast('externalSave');
  } catch (e) {
    // Sometimes, AngularJS throws a "Cannot read property $$nextSibling of
    // null" error. To get around this we must use $apply().
    $rootScope.$apply(function() {
      $rootScope.$broadcast('externalSave');
    });
  }
}

这是我到现在为止写的测试,但它不起作用(它从errorMessage 和 Jasmine 错误抛出错误:Error: Expected function to throw an Error.):

fit('should save pending changes', function() {
    var errorMessage = 'Cannot read property $$nextSibling of null'; 
    spyOn($rootScope, '$broadcast').and.throwError(errorMessage);
    expect(function() {
      RouterService.savePendingChanges();
    }).toThrowError(errorMessage);
  });

谁能帮我解决这个问题?谢谢!

【问题讨论】:

  • 在您的 AngularJS 函数中,您正在捕获错误 - 所以 Jasmine 没有检测到任何抛出的错误。所以我认为你可以测试 $apply 正在运行,但不能测试错误,因为它被 catch 吞噬了。
  • 我试过了,但没有用。经过几次尝试,我发现当 AngularJS 方法被监视到抛出错误时,由于某种原因,测试也会失败。所以我在第一次调用 $broadcast 后使用了一个 console.log 并监视了它。成功了!

标签: angularjs unit-testing testing jasmine karma-jasmine


【解决方案1】:

您可以检查广播是否被调用了两次:

fit('should save pending changes', function () {
    var errorMessage = 'Cannot read property $$nextSibling of null';
    var broadcastSpy = spyOn($rootScope, '$broadcast').and.throwError(errorMessage);

    RouterService.savePendingChanges();

    expect(broadcastSpy).toHaveBeenCalledTimes(2);
});

【讨论】:

    猜你喜欢
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多