AngularJS ctrl单元测试依赖项失败

时间:2018-07-30 18:09:09

标签: javascript angularjs unit-testing karma-jasmine

试图弄清楚为什么不检查依赖项是否存在导致测试失败?

var app = angular.module('app', []);
app.controller('MainCtrl', ['UserService', '$scope', '$q',  function(userServivce,$scope, $q){
    
  var userCall = userServivce.getUsers(); // working in controller but fail test
  
  //test paasses
  if(userServivce){
    var userCall = userServivce.getUsers()
  }
})

测试:

describe('MainCtrl', function () {
  var $scope, userService, $q, MainCtrl;
    
  beforeEach(module('app'));
  beforeEach(inject(function(_$controller_, _$rootScope_){
    MainCtrl = _$controller_;
    $scope = _$rootScope_.$new();
    MainCtrl('MainCtrl', {$scope: $scope, UserService: userService, $q: $q});
  }));

  it('should scope to be defined', function()  {
   
   expect($scope).toBeDefined();
  });
});

Angular.js 1.3 KarmaJasmine 如果没有,则语句出错:

TypeError:未定义不是对象(正在评估'userService.getUsers')     未定义     静态/js/app/controllers.js:9:2255     e@static/js/node_modules/angularjs/angular.min.js:36:320

Karma conf link

1 个答案:

答案 0 :(得分:1)

您指定了变量,但尚未定义userService属性:

var $scope, userService, $q, MainCtrl;

userService = {
    getUsers => function() {
        // logic, mock or return here
    }
};