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.
This Injected Dependencies become undefined in angular service is very similar to my issue but I couldn't translate the JS.
I have also changed my variable names and simplified the code to remove irrelevant lines.
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
}]));
});
});
The problem I'm having is that when I call ServiceAMethod I get an error which states "TypeError: Cannot read property 'property' of undefined". The weird thing is that $resource is never undefined but my ServiceB is always 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.
Update
I've also tried to inject an instance of my ServiceB into the it but when I print out the variable it also states that is it undefined, and when I try to to do the code below into the beforeEach
inject(function (_ServiceBInstance_: ServiceB) {
console.log(_ServiceBInstance_);
});
I get and Unknown Provider error.
Ok so after hours of searching I finally found the answer. I forgot to include a file which included Angular's .config method
When creating the provider make sure that you also call .config, here's an example: