WHAT: Testing an async function that uses await
WITH: Angular 9, Jasmine 3.4.0
Minimal code to reproduce: StackBlitz
I have a function like this. Note, that it has to await this.getHeaders(). Whenever I remove await and replace the implementation of getHeaders() by some synchonous implementation, the test runs successfully.
What is the correct way to test it?
private async loadUserData() {
// Try to remove await - the test runs successfully
//const headers = this.getHeaders();
const headers = await this.getHeaders();
return this.httpClient
.get<UserData>(window.location.origin + '/12345', { headers })
.toPromise()
.then((data) => {
this.userData = data;
})
.catch((e) => {
console.log('Oh noooo...');
});
}
WHAT I'VE TRIED:
- It might be the case that the url in StackBitz is not correct, but when testing locally I am sure it is, so this should not be the root cause
- not sure, if fakeAsync() will help - the "pure" http test works...
NOT A DUPE OF: