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

how to construct unit test for controller with $state?

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

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

我写了这个 jasmine 单元测试:

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

您已将 $state 本地分配给 state(规范中未定义的变量)而不是注入的 $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');