未捕获的TypeError:无法读取属性' service.method'未定义的

时间:2016-10-21 06:16:10

标签: angularjs karma-jasmine

describe('Controller:insightSettingsController', function() {
'use strict';
var insightSettingsCtrl;
var settingsService;
var UtilsService;
var scope;
var updateMethodDeferred;
var httpBackend;
var deferred;
var q;
var spy;
beforeEach(module('ui.router',proname.components.insightSettings.module.name));

beforeEach(function() {
var mockUtilsService = {};
module(function(_$provide_) {
  _$provide_.value('UtilsService', mockUtilsService);
});

inject(function($q) {
  deferred = $q.defer();
  mockUtilsService.getConfigurations = function() {};
  spyOn(mockUtilsService, 'getConfigurations')
      .and.returnValue(deferred.promise);
});

});
beforeEach(inject(function(
  _$controller_, _$httpBackend_, _$rootScope_, _settingsService_,
  _UtilsService_, _$q_) {
  scope = _$rootScope_.$new();
  spy = jasmine.createSpy();
  settingsService = _settingsService_;
  UtilsService = _UtilsService_;
  httpBackend = _$httpBackend_;
  insightSettingsCtrl = function() {
  return _$controller_(
      dbmcm.components.settings.insightSettingsController,
      {$scope: scope, UtilsService: UtilsService});
};

}));

describe(
'Check Existing Function , parameters, Initialization of function',
function() {
it('should call UtilsService.getConfigurations() once',
  function() {
    insightSettingsCtrl();
    deferred.resolve();
    scope.$digest();
    expect(UtilsService.getConfigurations).toHaveBeenCalled();
  });
});

});

嗨,我正在为单独的模块编写角度测试用例。不幸的是,上面的模块分解了我的测试用例,得到错误 debug.js:44未捕获的类型错误:无法读取属性'获取配置& #39;未定义。我在控制器初始化时触发 getConfigurations 功能请看下面

 constructor: function(UtilsService) {
 UtilsService.getConfigurations().then(function(response) {
   this.utilsConfig_ = response;
 }.bind(this));
}

我认为Jasmine的间谍只会检查函数是否被调用,而不会触发实际的实现。这就是getConfigurations()。然后抛出错误的原因。 为此我在我的测试用例中应用了.and.callThrough()

it('should call UtilsService.getConfigurations() once',
  function() {
   spyOn(UtilsService, 'getConfigurations').and.callThrough();
    insightSettingsCtrl();
    deferred.resolve();
    scope.$digest();
    expect(UtilsService.getConfigurations).toHaveBeenCalled();
  });
});

之后我得到 debug.js:44未捕获错误:getConfigurations已被监视

请纠正我在哪里做错了。 提前致谢

1 个答案:

答案 0 :(得分:1)

要么你嘲笑它,要么尽可能地注射它。

你正在为UtilsService做两件事。

我假设你注射了UtilsService

因此,请删除以下代码:

module(function(_$provide_) {
  _$provide_.value('UtilsService', mockUtilsService);
});

inject(function($q) {
  deferred = $q.defer();
  mockUtilsService.getConfigurations = function() {};
  spyOn(mockUtilsService, 'getConfigurations')
      .and.returnValue(deferred.promise);
})