在Jasmine中测试try / catch不起作用

问题描述 投票:0回答:1

我有我要测试的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 unit-testing testing jasmine karma-jasmine
1个回答
0
投票

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

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);
});
© www.soinside.com 2019 - 2024. All rights reserved.