如何在AngularJS中广播测试事件?

时间:2013-10-14 02:24:00

标签: unit-testing angularjs

我只是想知道如何测试handleAddClientBroadcast事件?

我有这样的导航服务:

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

        var navigationService = {};

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

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

        return navigationService;
    });

我将此导航服务注入我的clientsCtrl并抓住handleAddClientBroadcast,如下所示:

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

感谢。

1 个答案:

答案 0 :(得分:8)

假设你正在使用Jasmine

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

...

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