使用$ injector测试AngularJS服务时如何注入依赖项

时间:2015-05-12 14:22:07

标签: angularjs unit-testing karma-jasmine

我正在尝试测试我编写的服务,但该服务包含$http模块。如何将依赖项注入使用$injector为模块提供的服务检索的模块?

以下是示例代码:

服务

var app = angular.module('myServiceApp', [])
.service('CommonService', ['$http', CommonService]);

function CommonService($http) {
  var Service = {};
  // ...code
  return Service;
}

测试代码

describe('My Common App', function() {
  var Service;

  beforeEach(function() {
    var $injector = angular.injector('myServiceApp');
    Service = $injector.get('CommonService');
  });
});

错误

Error: [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=%24httpProvider%20%3C-%20%24http%20%3C-%20CommonService

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用ng mock

var service;

beforeEach(mocks.module('myServiceApp'));
beforeEach(mocks.inject(function (CommonService) {
    service = CommonService;
}));

答案 1 :(得分:0)

我通过以下方式解决了这个问题:

function validatorDayOfMonth(v) {
  // Obviously replace the year with the correct value to account for leap years.
  // Within a validation function `this` refers to the root document being validated.
  return ((v === '*') || new Date(2015, this.date.months, v).getDate() === v);
};