如何用$ state构造控制器的单元测试?

时间:2015-05-26 05:52:12

标签: angularjs unit-testing angular-ui-router karma-jasmine

尝试为我的控制器编写单元测试:

 app.controller('StartGameCtrl', function ($scope, $timeout,$state) {
      $scope.startGame = function () {
        $scope.snap = false;
        $scope.dealCards();
        debugger;
        $state.go('cpu');
      }
    });

我写了这个茉莉花单元测试:

describe('snap tests', function() {
  beforeEach(module('snapApp'));
  var scope, createController, state;

  beforeEach(inject(function ($rootScope, $controller,$state) {
    scope = $rootScope.$new();
    createController = function () {
      return $controller('StartGameCtrl', {
        '$scope':scope,
        '$state':state
      });
    };
  }));


  it('startGame should call dealcards', function () {
    var controller = createController();
    spyOn(scope, 'dealCards');
    scope.startGame();
    //expect(scope.dealCards).toHaveBeenCalled();
  });

});

当我进行业力测试时,我收到一个错误:

TypeError: 'undefined' is not an object (evaluating '$state.go')
at startgamectrl.js:9

1 个答案:

答案 0 :(得分:1)

您已将$state本地分配为state(规范中未定义的var),而不是注入的$state服务。

不是这样做,而是为$state创建一个间谍。例如......

beforeEach(inject(function ($rootScope, $controller) {
    scope = $rootScope.$new();
    state = jasmine.createSpyObj('$state', ['go']);
    createController = function () {
        return $controller('StartGameCtrl', {
            '$scope':scope,
            '$state':state
        });
    };
}));

然后你可以测试它被称为

expect(state.go).toHaveBeenCalledWith('cpu');
相关问题