jeudi 24 mars 2016

Unit Testing a Service but its Dependencies Evaluate to undefined

I'm new to Angular and I'm not quite sure exactly how dependency injection works. My problem is that I have Service A which depends on Service B, but when I inject Service A into my test Service B becomes undefined.

I have seen Injecting dependent services when unit testing AngularJS services but that problem is a bit different than mine.

I have also changed my variable names and simplified the code to remove irrelevant lines.

Service.ts

export class ServiceA {
    constructor(private ServiceBInstance: ServiceB){
    }

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

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

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

Spec.ts

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

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

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

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

});

The problem I'm having is that when I call ServiceAMethod I get an error which states "TypeError: Cannot read property 'property' of undefined".

I thought that when I inject ServiceA into my test it should automatically also inject all of its dependencies.

Also note that I am not mocking ServiceB on purpose.

Aucun commentaire:

Enregistrer un commentaire