There’s several tutorials for how to use and test HttpClient, but I wanted to distill it down to a simple snippet that I can refer back to when I inevitably forget how to do it.
HttpTestingController
This handy thing is provided by importing the HttpClientTestingModule in to your TestBed. It lets you manipulate all of the HttpClient calls and verify that things are happening the way that you want them to.
The HttpTestingController can then be easily used to set up the routes that you’re expecting and the results from those routes. Then, you can just call verify() to automatically run assertions on your expectations.
Peter
Awesome! 🙂
…but what about that version:
it(‘should call the api’, async () => {
const expected = { name: ‘Wiggles’, age: 25 };
const response = await service.Get().toPromise();
httpMock.expectOne(‘api/getstuff’).flush(expected);
const result = await response;
expect(result.name).toBe(‘Wiggles’);
expect(result.age).toBe(25);
httpMock.verify();
});
Btw. in
expect(result.name).toBe('Wiggles');
you should always hard-coded expected value.Robert
Hey Peter,
Yeah, that test looks legit to me! I’m not sure I agree with always using hard-coded expected values — I tend to typo a lot, so I like to make constants at the beginning of a test to outline the expected values, just in case I need to type them more than once. I’ve blogged a lot about not liking magic strings, so having hard-coded values in the expect seems magic string-y to me.