我该如何测试这种ng-click方法?

时间:2015-07-23 13:42:57

标签: javascript angularjs unit-testing jasmine karma-runner

我使用ng-click语法将以下方法绑定到scope上的controllerAs

vm.setCap = function(cap) {
  playersService.setCap(
    {playerId: playerId},
    {limit: cap}
  ).$promise.then(function() {
    alert('success');
  }, function() {
    alert('error');
  });
};

我想测试的是,当我致电vm.setCap时,使用正确的参数调用playersService.setCap一次。

这是我尝试过的,但我继续误解了错误:

it('should call a setCap method', function() {
  spyOn(playersService, 'setCap');
  expect(PlayersController.setCap).toBeDefined();
  PlayersController.setCap(1000);
  expect(playersService.setCap).toHaveBeenCalled();
});

错误:

TypeError: 'undefined' is not an object (evaluating 'playersService.setCap({playerId:playerId},{limit:cap}).$promise')

1 个答案:

答案 0 :(得分:0)

在您的控制器中,将playersService附加到vm,然后执行此操作:

spyOn(PlayersController.playerService, 'setCap');

所以你的控制器看起来像这样:

vm.playersService = playersService;
vm.setCap = function (cap) {
    playersService.setCap({
        playerId : playerId
    }, {
        limit : cap
    }).$promise.then(function () {
        alert('success');
    }, function () {
        alert('error');
    });
};

测试不知道你的playerService变量,因为它是控制器的本地变量,通过将它附加到你可以运行测试的虚拟机。