I have Angular HTTP service that makes some HTTP-calls. Here's an example of my service:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class APIService {
constructor(private readonly http: HttpClient) {}
public async getUsers<T>(): Promise<T[]> {
return await this.http.get<T[]>('/api/users').toPromise();
}
}
And here's my spec.ts
file for APIService
:
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { APIService } from './api.service';
describe('API Service', () => {
let service: APIService;
let controller: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [APIService]
});
service = TetsBed.get(APIService);
controller = TestBed.get(HttpTestingController);
});
it('should create the API service', () => {
expect(service).toBeTruthy();
});
it('should get users', () => {
const expected = [{id: 1, email: 'email1@domain.tld'},
{id: 2, email: 'email2@domain.tld'}];
service.getUsers<MyUserClass>().then((res) => {
expect(res).toEqual(expected);
controller.verify();
});
controller.expectOne('/api/users').flush(expected);
});
});
Everything seems to works, cause when I run ng test
, I have message like this:
ERROR: 'Spec 'API Service should get users' has no expectations.'
HeadlessChrome 77.0.3865 (Windows 10.0.0): Executed 13 of 15 SUCCESS (0 secs / 0.256 secs)
HeadlessChrome 77.0.3865 (Windows 10.0.0): Executed 15 of 15 SUCCESS (0.42 secs / 0.28 secs)
TOTAL: 15 SUCCESS
TOTAL: 15 SUCCESS
TOTAL: 15 SUCCESS
When I change something under next code, I got error.
.then((res) => {
// expect(res).toEqual(expected);
expect(res).toBeNull();
controller.verify();
});
So code above is fine and working.
Then, why I have an error message with ERROR: 'Spec 'API Service should get users' has no expectations.'? Any ideas?
I guess, async/await might cause this problem, cause I don't actually wait for it, however, it executes with no error, and when I put wrong data, then it fails.
I also tried to wrap everything into async
/fakeAsync
methods - no luck.