title: How can I test Broadcast event in AngularJS
body: <p>I have a controller which emits a broadcast event on the rootscope. I would like to test that the broacast event is fired correctly.</p>
  
  <p>My code in my controller looks like this:</p>
  
  <pre><code>   $scope.$watch("pageIndex", function(){
      if($scope.pageIndex == 4)
      {
        // emit social share
        $rootScope.$broadcast('myEvent');
      }
    });
  </code></pre>
  
  <p>I have tried to test it with the following code:</p>
  
  <pre><code>    it('Should call myEvent when pageIndex is 4',function(){
      scope.pageIndex = 4;
      scope.$apply();
      expect(rootScope.$on).toHaveBeenCalledWith('myEvent');
  });
  </code></pre>
  
  <p>But it tells me that the code isn't called, which I have manually tested that it does. I have then tried with the following code:</p>
  
  <pre><code>it('Should call myEvent when pageIndex is 4',function(){
      var listener = jasmine.createSpy('listener');
      rootScope.$on('myEvent', listener);
      scope.pageIndex = 4;
      scope.$apply();
      expect(listener).toHaveBeenCalled();
  });
  </code></pre>
  
  <p>But with the same negative result. Is there a way to test that an event is broadcasted?</p>