【问题标题】:how to construct unit test for controller with $state?如何使用 $state 为控制器构建单元测试?
【发布时间】:2015-05-26 05:52:11
【问题描述】:

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

 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

【问题讨论】:

  • 您的snapApp 模块中是否包含ui.router 模块?

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


【解决方案1】:

您已将 $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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2019-08-23
    相关资源
    最近更新 更多