单元测试中未定义注入的依赖关系

时间:2016-03-24 13:56:13

标签: angularjs unit-testing dependency-injection jasmine

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

我见过Injecting dependent services when unit testing AngularJS services,但问题与我的有点不同。

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

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

Service.ts

"aux_var":1

Spec.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);

});

我遇到的问题是,当我调用ServiceAMethod时,我收到一条错误,指出“TypeError:无法读取未定义的属性'属性'。奇怪的是,$ resource永远不会被定义,但我的ServiceB总是未定义的。

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

另请注意,我并非故意嘲笑ServiceB。

更新

我还尝试将我的ServiceB实例注入,但是当我打印出变量时,它还说明它是未定义的,当我尝试执行下面的代码时进入 beforeEach

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
            }]));
    });

我得到未知提供商错误。

1 个答案:

答案 0 :(得分:0)

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

的文件

创建提供程序时,请确保也调用.config,这是一个例子:

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