测试$ broadcast事件

时间:2014-07-14 19:11:20

标签: angularjs jasmine

角度测试有问题。我试图测试$ broadcast被成功解雇了。我试图使用spyOn时有一些奇怪的行为。如果您有任何建议,请帮助我一直试图解决这个问题几个小时。我的测试看起来像这样:

describe('Signup controller', function() {

  beforeEach(module('myApp'));

  describe('SignupCtrl', function(){
    var $scope, ctrl, $httpBackend, AUTH_EVENTS, $rootScope;

    beforeEach(inject(function($injector, $controller,
      _$httpBackend_, _apiUrl_, _AUTH_EVENTS_){

        $rootScope = $injector.get('$rootScope');
        $scope = $rootScope.$new();
        ctrl = $controller('SignupCtrl', {$scope: $scope});
        $httpBackend = _$httpBackend_;
        apiUrl = _apiUrl_;
        AUTH_EVENTS = _AUTH_EVENTS_;
        spyOn($rootScope, "$broadcast");
      }
    ));

    afterEach(function() {
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

    it('should show error message from API', function() {
      var apiMessage = 'That email already exists.';
      $httpBackend.expectPOST('/users').respond(400, {
        message: apiMessage
      });

      // call controller register function with mock empty credentials
      $scope.register({});

      $httpBackend.flush();
      expect($rootScope.$broadcast).toHaveBeenCalledWith(AUTH_EVENTS.signupFailed);
      expect($scope.errorMessage).toBe(apiMessage);
      expect($scope.showErrorMessage).toBe(true);
    });

  });
});

我得到的错误是:

TypeError: 'undefined' is not an object (evaluating '$rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
            defaultPrevented')
  at /src/web/src/vendor-bower/angular/angular.js:9789
  at /src/web/src/vendor-bower/angular/angular.js:12595
  at /src/web/src/vendor-bower/angular/angular.js:12407
  at /src/web/src/vendor-bower/angular-mocks/angular-mocks.js:1438

1 个答案:

答案 0 :(得分:12)

试试spyOn(rootScope,'$broadcast').andCallThrough();,让我知道它是怎么回事。另见我的评论。

相关问题