Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular test service with dependencies

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?

like image 765
Teodor Dimitrov Avatar asked Oct 03 '17 15:10

Teodor Dimitrov


People also ask

How do you test a service with dependencies?

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).

How do you inject a service in component Angular test?

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.

Which method is used to mock the service method response in Angular?

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.

What is fixture detectChanges ()?

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.


1 Answers

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]
});
like image 190
Teodor Dimitrov Avatar answered Sep 18 '22 17:09

Teodor Dimitrov