I'm trying to set up a test for my service using TestBed. That service has some dependencies of other services. I've created .stub files for those dependencies and exported them. Problem is when I try to use these stubs in the test it still seems like the test methods use the real service and not the test. Here's my setup (the fake names are just for this thread):
describe('ServiceToTest', () => {
let stubbedService: ServiceDependency1;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
providers: [
ServiceToTest,
{ provide: ServiceDependency1, useClass: ServiceDependency1Stub },
{ provide: ServiceDependency2, useClass: ServiceDependency2Stub }
]
});
stubbedService = TestBed.inject(ServiceDependency1);
});
it('description', fakeAsync(() => {
// Error appears here when trying to use the BehaviorSubject on the mock:
// Property 'behaviorSubjectTest' does not exist on type
'ServiceDependency1'
stubbedService.behaviorSubjectTest.next(new Test());
... more logic
}));
});
I understand the error, that's because behaviorSubjectTest
property is on the stub and not the real service. But why doesn't it use the stub service when I listed it as a useClass
in the providers?
What am I doing wrong? When I see what's available on serviceDependency1Stub
I see all the methods and properties on the real service and not the stub. This happened after updating to Angular 9. Earlier we used the .get
method and then it worked. Then it was set up like this:
describe('ServiceToTest', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
providers: [
ServiceToTest,
{ provide: ServiceDependency1, useClass: ServiceDependency1Stub },
{ provide: ServiceDependency2, useClass: ServiceDependency2Stub }
]
});
});
it('description', fakeAsync(() => {
const stubbedService = TestBed.get(ServiceDependency1);
stubbedService.behaviorSubjectTest.next(new Test());
... more logic
}));
});
And here's the .stub file:
export class ServiceDependency1Stub {
public behaviorSubjectTest = new BehaviorSubject<Test>(null);
}
I guess the setup from start was wrong, but not exposed before now after changing to .inject
?
I've looked at the documentation but I can't find any good examples on testing service with dependencies. If anyone could help me and point me in the right direction I would appreciate that.
Thanks.