Reputation: 134
i am testing a service in angular(1.6.3) My service is dependent on another service. every time i run ng test i get no provider for ServiceName or HTTpclient any help???? service:
export class TraitsService {
constructor(private gs: GenericService) {}
getAll(callback: Function) {
this.gs
.callGet(`${environment.serviceURL}${environment.serviceConfigAPI.getMyTraits}?active=true`)
.subscribe(traits => callback(this.flatten(traits)));
}
test:
describe('TraitsService', () => {
let service: TraitsService;
let gs: GenericService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [TraitsService, GenericService]
});
service = TestBed.get(TraitsService);
gs = TestBed.get(GenericService);
});
it('should be created', inject([TraitsService], (service: TraitsService) => {
expect(service).toBeTruthy();
}));
Upvotes: 2
Views: 3008
Reputation: 6060
This is dealt with extensively in the Official Documentation, but it can be a bit intimidating to start with. :)
As the documentation points out, there are many ways you can test this. I personally tend to prefer spying on the original service to test the one under consideration in isolation. I have put together a Stackblitz for you to demonstrate how you could do this in your case.
From that Stackblitz, here is the describe()
function in the .spec file:
describe('TraitsService', () => {
const mockReturnValue = [1, 2, 3]; // change this!
const gsSpy = jasmine.createSpyObj('GenericService', ['callGet']);
gsSpy.callGet.and.returnValue(of(mockReturnValue));
let service: TraitsService;
// let gs: GenericService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
TraitsService,
{ provide: GenericService, useValue: gsSpy }
]
});
service = TestBed.get(TraitsService);
// gs = TestBed.get(GenericService);
});
it('should be created', inject([TraitsService], (service: TraitsService) => {
expect(service).toBeTruthy();
}));
});
You can see in the Stackblitz that the service creates correctly. I hope this helps.
Upvotes: 3