2

I am just wondering how can I test the handleAddClientBroadcast event?

I have a navigation service like so:

angular.module("ruleManagement.services")
    .factory('navigationService', function ($rootScope) {

        var navigationService = {};

        navigationService.prepForBroadcast = function() {
          this.broadCastIsAddClientItem();
        };

        navigationService.broadCastIsAddClientItem = function() {
          $rootScope.$broadcast('handleAddClientBroadcast');
        };

        return navigationService;
    });

I inject this navigation service into my clientsCtrl and catch the handleAddClientBroadcast like so:

$scope.$on('handleAddClientBroadcast', function () {
  $scope.clientModel = {
    id: 0,
    name: "",
    description: "",
    rules: []
  };

  var lastClient = _.findLast($scope.clients);

  if (typeof lastClient == 'undefined' || lastClient == null) {
    lastClient = $scope.clientModel;
  }

  $scope.clientModel.id = lastClient.id + 1;
  $scope.clients.push($scope.clientModel);
});

Thanks.

Ben
  • 54,723
  • 49
  • 178
  • 224
willwin.w
  • 174
  • 1
  • 9
  • I found this helpful too: http://stackoverflow.com/questions/15272414/how-can-i-test-events-in-angular – Ben Aug 16 '14 at 01:48
  • possible duplicate of [How do I test $scope.$on in AngularJS](http://stackoverflow.com/questions/19441782/how-do-i-test-scope-on-in-angularjs) – ivarni Sep 30 '14 at 09:37

1 Answers1

8

Assuming you're using Jasmine

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

...

expect($rootScope.$broadcast).toHaveBeenCalledWith('eventName');
ivarni
  • 17,658
  • 17
  • 76
  • 92