Highlighting testing streams using HttpClientTestingModule
Observables that are returned from the HTTP client are frequently used in our Angular code. How can we test those streams? Let's look at the pattern we can use to test those observables. We will consider the following method inside RecipeService
:
saveRecipe(formValue: Recipe): Observable<Recipe> { return this.http.post<Recipe>( `${BASE_PATH}/recipes/save`, formValue); }
The saveRecipe
method issues an HTTP request. There is a very useful API that can be used in this case: HttpClientTestingModule
. This API allows us to test HTTP methods that use the HTTP client. It also allows us to easily mock HTTP requests by providing the HttpTestingController
service. In short, it enables us to mock requests instead of making real API requests to our API backend when testing.
Let's look at the pattern's steps:
- Before...