如何在 Karma 中使用参数测试$on事件

How to test $on event with parameters in Karma

本文关键字:参数测试 on 事件 Karma      更新时间:2023-09-26

我有控制器代码:

$scope.$on('load', function (event) {
    $scope.getData();
    event.stopPropagation();
});

和测试代码:

it('$on load', function(event) {
    var controller=createController();
    spyOn(scope, '$on').andCallThrough();// I have also tried to spy scope getData
    scope.$broadcast('load');
    expect(scope.$on).toHaveBeenCalledwith("load");
});

类型错误:event.stopPropagation 不是函数

如何在单元测试的调用中定义参数?

个角度想...

如果你在作用域上触发加载事件,那么你期望 getData 已被调用......

在getData上放置一个间谍,然后你可以期望该函数被调用。

我测试这种方法的方法是将间谍放在$broadcast上。

 spyOn($scope, '$broadcast').and.callThrough();
 spyOn(event, 'preventDefault').and.callFake(function() {});

然后在描述块中

describe('load event', function() {
  it('should call getData method', function() {
      $scope.$broadcast('load');
      expect($scope.getData).toHaveBeenCalled();
    });
});