Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing $broadcast event

I have a problem with angular tests. I'm trying to test that $broadcast was successfully fired. I'm having some strange behavior trying to use spyOn. If you have any suggestions please help I've been trying to solve this for hours. My test looks like this:

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);
    });

  });
});

And the error I'm getting is:

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
like image 710
iblazevic Avatar asked Dec 14 '22 21:12

iblazevic


1 Answers

Try spyOn(rootScope,'$broadcast').andCallThrough(); and let me know how it goes. Also see my comment.

like image 169
Alex C Avatar answered Jan 20 '23 19:01

Alex C