我有一个这样定义的服务:
angular.module("myApp")
.factory("myService.foo", function () {
// utterly delightful code
});
我正在使用 Karma 和 Jasmine 进行测试。在测试中,我对我的大部分服务器测试都在做这样的事情:
describe('Service: someService', function () {
// load the service's module
beforeEach(module('myApp'));
// instantiate service
var _someService;
beforeEach(inject([function (someService) {
_someService = someService;
}]));
it('should do something', function () {
expect(!!_someService).toBe(true);
});
});
当我尝试对名为“myService.foo”的服务执行相同操作时,它会抛出错误(当然):
describe('Service: myService.foo', function () {
// load the service's module
beforeEach(module('myApp'));
// instantiate service
var _myService;
beforeEach(inject([function (myService.foo) {
_myService = myService.foo;
}]));
it('should do something', function () {
expect(!!_myService).toBe(true);
});
});
由于点语法的明显问题使得 Angular 无法推断服务名称。我怎样才能注入(inject)这个服务来测试它?我是否缺少一些替代语法?
最佳答案
可以使用数组表示法,例如:
var _myService;
beforeEach(inject(['myService.foo', function (myService) {
_myService = myService;
}]));
注意(来自 documentation ):
It is important that the order of the string identifiers in the array is the same as the order of argument names in the signature of the factory function. Unless the dependencies are inferred from the function signature, it is this array with IDs and their order that the injector uses to determine which services and in which order to inject.
关于angularjs - Angular & Jasmine : how to inject services with dots in their names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19963019/