mardi 26 juillet 2016

Difficulty testing this $on in my app's controller. Angular JS

In my directive controller, I listen out for a click event:

$scope.showPanel = function(panelName) {

    if(panelName === 'panelOne'){
        $rootScope.$broadcast('panelOne_selected'); 
    }

     if(panelName === 'panelTwo'){
        $rootScope.$broadcast('panelTwo_selected'); 
    }                   
}

I broadcast that event up to my applications parent controller:

$scope.$on('panelOne', 
    function(event) {
        $scope.panelOne = true;
        $scope.panelTwo = false; 
    }
)

I'm having trouble testing this $on though, my test looks like this:

it(
  'Check events broadcast to app controller properly',
    inject(function($controller, $rootScope) {

      var scope = $rootScope.$new();
      var rootScope = $rootScope;

      spyOn(rootScope, '$broadcast').andCallThrough();
      spyOn(rootScope, '$on').andCallThrough();

      $controller('MainApplicationController', {
        $scope: scope,
        $element: {},
        $attrs: {},
        $transclude: {}
      });

      scope.showPanel('panelOne');
      expect(scope.$broadcast).toHaveBeenCalledWith('panelOne_selected');
      expect(scope.$on).toHaveBeenCalledWith('panelOne_selected');

      $rootScope.$digest();

  })
);

My tests is failing with the following:

Expected spy $on to have been called with [ 'panelOne_selected' ] but it was never called.

If I remove expect(scope.$on).toHaveBeenCalledWith('panelOne_selected');, the tests passes.

Can anyone tell me what I'm doing wrong here?

Aucun commentaire:

Enregistrer un commentaire