【问题标题】:Injected Dependency is undefined in Unit Test在单元测试中未定义注入的依赖项
【发布时间】:2016-07-12 03:28:43
【问题描述】:

我是 Angular 的新手,我不太确定依赖注入是如何工作的。我的问题是我有依赖于服务 B 的服务 A,但是当我将服务 A 注入我的测试服务 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:无法读取未定义的属性 'property'”。奇怪的是 $resource 永远不会未定义,但我的 ServiceB 始终未定义。

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

另外请注意,我不是故意嘲笑 ServiceB。

更新

我也尝试将我的 ServiceB 的实例注入到 it 中,但是当我打印出变量时,它还指出它是未定义的,并且当我尝试执行以下代码时进入beforeEach

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

我得到 Unknown Provider 错误。

【问题讨论】:

    标签: angularjs unit-testing dependency-injection jasmine


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-19
      • 1970-01-01
      • 2021-05-17
      • 2018-01-11
      • 2017-04-01
      • 2017-02-07
      • 1970-01-01
      相关资源
      最近更新 更多