角度茉莉花服务测试广播未调用

时间:2014-09-16 16:10:17

标签: angularjs unit-testing jasmine karma-jasmine

我有一个相当简单的服务,基本上捕获错误,使用特定的错误类型和错误消息增强它们并广播错误事件,以便我的应用程序的某些部分可以处理问题。可以找到简化版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功能中的事实有关。有没有人知道如何让测试运行?

1 个答案:

答案 0 :(得分:1)

您已拒绝承诺,但您需要在测试之前调用摘要周期,以便调用promise的错误回调。

执行: -

     $q.reject('error').catch(errors.catch('type', 'message'));

     rootScope.$digest();

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

<强> Demo

相关问题