gpt4 book ai didi

angularjs - 注入(inject)的依赖项在单元测试中未定义

转载 作者:行者123 更新时间:2023-12-05 07:50:25 29 4
gpt4 key购买 nike

我是 Angular 的新手,我不太清楚依赖注入(inject)是如何工作的。我的问题是我有依赖于服务 B 的服务 A,但是当我将服务 A 注入(inject)我的测试服务 B 时,服务 B 变得未定义。

我看过Injecting dependent services when unit testing AngularJS services但是这个问题和我的有点不同。

Injected Dependencies become undefined in angular service与我的问题非常相似,但我无法翻译 JS。

我还更改了变量名并简化了代码以删除不相关的行。

Service.ts

export class ServiceA {
constructor(private $resource: ng.resource.IResourceService, private ServiceBInstance: ServiceB){
}

ServiceAMethod() {
var resources = ServiceBInstance.property; //ServiceBInstance is undefined here
}
}

factory.$inject = [
'$resource'
'ServiceBModule'
];
function factory($resource: ng.resource.IResourceService, ServiceBInstance: ServiceB): IServiceA {
return new ServiceA($resource, ServiceBInstance);
}

angular
.module('ServiceAModule')
.factory('ServiceA',
factory);

Spec.ts

describe('ServiceB', (): void => {

beforeEach((): void => {
angular.mock.module(
'ServiceAModule',
'ServiceBmodule',
'ngResource'
);
});

describe('ServiceAMethod', (): void => {

it("should...", inject(
['ServiceA', (ServiceAInstance: ServiceA): void => {
ServiceAInstance.ServiceAMethod(); //Problem Here
}]));
});

});

我遇到的问题是,当我调用 ServiceAMethod 时,我收到一条错误消息,指出 “TypeError: Cannot read property 'property' of undefined”。奇怪的是 $resource 永远不会是未定义的,但我的 ServiceB 总是未定义的。

我认为当我将 ServiceA 注入(inject)到我的测试中时,它应该也会自动注入(inject)它的所有依赖项。

另请注意,我并不是故意 mock ServiceB。

更新

我也尝试将我的 ServiceB 的一个实例注入(inject)到 it 但是当我打印出变量时它还指出它是未定义的,当我尝试执行下面的代码时进入beforeEach

inject(function (_ServiceBInstance_: ServiceB) {
console.log(_ServiceBInstance_);
});

我遇到了Unknown Provider 错误。

最佳答案

好的,经过几个小时的搜索,我终于找到了答案。我忘记包含一个包含 Angular 的 .config 方法的文件

创建提供程序时,请确保您还调用了 .config,这是一个示例:

angular
.module('ServiceBModule')
.config(['ServiceBProvider', (ServiceBClass) => { //Very Important
//Code here
}])
.provider('ServiceB', ServiceB);

关于angularjs - 注入(inject)的依赖项在单元测试中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36201905/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com