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

时间:2022-10-02 23:07:17

I am trying to test a service I wrote but the service includes the $http module. How can I inject a dependency into a module that was retrieved using $injector for a service provided by the module?

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

Below is the sample code:

以下是示例代码:

Service

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

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

Testing Code

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

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

Error

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

2 个解决方案

#1


Have you tried using ng mock?

你尝试过使用ng mock吗?

var service;

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

#2


I solved it by doing the following instead:

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

beforeEach(module('myServiceApp'));

beforeEach(inject(function(_CommonService_) {
  CommoService = _CommonService_;
}));

#1


Have you tried using ng mock?

你尝试过使用ng mock吗?

var service;

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

#2


I solved it by doing the following instead:

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

beforeEach(module('myServiceApp'));

beforeEach(inject(function(_CommonService_) {
  CommoService = _CommonService_;
}));