I have a service which depends on another service. I want to test it.
My Service:
@Injectable()
export class LanguageService {
constructor(private translate: TranslateService) {
}
My Test:
describe('LanguageService', () => {
let service: LanguageService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [LanguageService]
});
service = TestBed.get(LanguageService);
});
it('should set a preferred language', () => {
// Some test
});
});
When I run the test I get No provider for TranslateService. TranslateService depends on other dependencies and so on.
How can I add TranslateService dependency? Is there a way to do it without listing its numerous dependencies too?
Angular services can be tested in a couple of different ways, two most prominent being isolated tests and using the Angular TestBed . However, things get interesting when the service under test has dependencies (injected using Angular's dependency injection).
We can inject the service as following. empService = TestBed. inject(EmployeeService); In our example we will inject a simple service as well as a service with HttpClient dependency.
Prefer spies as they are usually the best way to mock services. These standard testing techniques are great for unit testing services in isolation. However, you almost always inject services into application classes using Angular dependency injection and you should have tests that reflect that usage pattern.
fixture is a wrapper for our component's environment so we can control things like change detection. To trigger change detection we call the function fixture.detectChanges() , now we can update our test spec to: Copy it('login button hidden when the user is authenticated', () => { expect(el. nativeElement.
The problem was that I was using ngx-translate inside my LanguageService. It needs some imports in order to work. After I've included them it worked fine.
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})],
providers: [LanguageService]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With