Skip to content
Advertisement

Angular: Unittest with async input pipe + mock service with HttpClient

I try to create a unittest for my angular component. The test case should do the following:

  1. Manipulate the input with “The”
  2. Check if the loading indicator is shown
  3. Return a mocked value from the service (which would normaly create a HttpRequest)
  4. Check if the loading indicator is hidden
  5. Check if the options of the response from the mocked service are shown
  6. [optional] Select an option and check the formControl value

First of all my component.ts:

JavaScript

The HTML file:

JavaScript

Here is my current unittest. I was not able to find an example for my usecase. I tried to implement the test, like they did it in the angular docs. I also tried the fixture.debugElement.query(By.css('input')) to set the input value and used the nativeElement, inspired by this post, neither worked. I am not so familiar with angular unittests. In fact I might not have understood some base concepts or principles.

JavaScript

Advertisement

Answer

The point of unit tests are that they should be small. Of course you can write 1 to 6 as one unit test but it will be confusing. Think of unit tests as I do this, I get that (one action, one reaction).

JavaScript

You don’t need to manually call ngOnInit since the first fixture.detectChanges() after component = calls ngOnInit for you and ngOnInit only populates an observable stream for you.

This seems to be a good source for Angular Unit Testing although I haven’t read all of it.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement