willwin.w
willwin.w

Reputation: 174

How do I test an event has been broadcast in AngularJS?

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.

Upvotes: 2

Views: 1683

Answers (1)

ivarni
ivarni

Reputation: 17878

Assuming you're using Jasmine

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

...

expect($rootScope.$broadcast).toHaveBeenCalledWith('eventName');

Upvotes: 8

Related Questions