【问题标题】:How do I test an event has been broadcast in AngularJS?如何测试已在 AngularJS 中广播的事件?
【发布时间】:2013-10-14 02:23:59
【问题描述】:

我只是想知道如何测试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);
});

谢谢。

【问题讨论】:

标签: unit-testing angularjs


【解决方案1】:

假设你正在使用 Jasmine

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

...

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

【讨论】:

  • 它是茉莉花的更高版本它是 spyOn(scope, '$broadcast').and.callThrough();
猜你喜欢
  • 2013-05-21
  • 2015-07-29
  • 1970-01-01
  • 2020-05-13
  • 2020-01-17
  • 1970-01-01
  • 2013-09-22
  • 2015-10-20
  • 1970-01-01
相关资源
最近更新 更多