【问题标题】:Angular Jasmine Service Testing broadcast not called未调用 Angular Jasmine 服务测试广播
【发布时间】:2014-09-16 16:10:16
【问题描述】:

我有一个相当简单的服务,它基本上可以捕获错误,使用特定的错误类型和错误消息增强它们并广播错误事件,以便我的应用程序的部分可以处理问题。简化版可以在here找到。

服务看起来像这样:

angular
  .module('app', [])
  .factory('errors', function ($rootScope) {
    function broadcast (error) {
      $rootScope.$broadcast('err:'+error.type, error.message, error.error);
    }
    return {
      catch: function (type, message) {
        return function (error) {
          broadcast({
            type: type,
            message: message,
            error: error
          });
        };
      }
    };
  });

现在我想用 Jasmine 测试该服务是否确实广播了错误。

为此,我编写了以下测试。

describe("errors: Errors (unit testing)", function() {
  "use strict";

  var errors,
      rootScope;

  beforeEach(function(){
    module('app');

    inject(function (_errors_, $injector) {
      errors = _errors_;
      rootScope = $injector.get('$rootScope');
      spyOn(rootScope, '$broadcast');
    });
  });

  it('should broadcast error event', inject(function ($q) {
    $q.reject('error')
      .catch(errors.catch('type', 'message'));

    expect(rootScope.$broadcast).toHaveBeenCalled();
  }));

很遗憾,测试从未通过,因为从未调用过 rootScope.$broadcast

我不确定,但我认为这与广播被封装在私有 broadcast 函数中这一事实有关。有人知道如何让测试运行吗?

【问题讨论】:

    标签: angularjs unit-testing jasmine karma-jasmine


    【解决方案1】:

    你已经拒绝了promise,但是你需要在测试之前调用digest循环,以便调用promise的错误回调。

    做:-

         $q.reject('error').catch(errors.catch('type', 'message'));
    
         rootScope.$digest();
    
         expect(rootScope.$broadcast).toHaveBeenCalled();
    

    Demo

    【讨论】:

    • 哦,哇,谢谢,这实际上很容易解决!我应该考虑到这一点。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2017-01-08
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多