测试$ broadcast事件

ibl*_*vic 4 jasmine angularjs

角度测试有问题.我正试图测试$ 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);
    });

  });
});
Run Code Online (Sandbox Code Playgroud)

而我得到的错误是:

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
Run Code Online (Sandbox Code Playgroud)

Ale*_*x C 12

试着spyOn(rootScope,'$broadcast').andCallThrough();告诉我它是怎么回事.另见我的评论.

  • 它确实有效.谢谢亚历克斯,这让我烦恼了一段时间.在jamsine 2.0中只有一个注释,它的and.callThrough(); (4认同)