Reputation: 30892
In an angular 2 application, I have a data service that converts the http observables to promises, in order to use the async/await sweetness, something like this:
async getCustomer(id: number): Promise<Customer> {
return await this._http.get<Customer>(`${this.serverUrl}/customer/${id}`).toPromise();
}
This is operational and looks and works great.
My previous unit tests used the MockBackend
with something like
mockBackend.connections.subscribe(c => {
expect(c.request.url).toBe(`${serverUrl}/customer/${id}`);
let response = new ResponseOptions({ body: mockResponseBody });
expect(c.request.method).toBe(RequestMethod.Get);
c.mockRespond(new Response(response));
});
let actual = await service.getCustomer(id);
However, now when I try something like this with
httpMock = TestBed.get(HttpTestingController);
// ... 1
let actual = await service.getCustomer(id);
// ... 2
I'm getting in a chicken-and-egg situation. The getCustomer
method will not return until a mocked request is provided, and I cannot use httpMock.expectOne
or httpMock.match
until the http call is triggered.
So if I put a httpMock
call in [1], I'm getting an expectation fail, and if I put it in [2], I'm getting a timeout error :(
Is there a way around this?
Upvotes: 1
Views: 2214
Reputation: 29916
I don't know how TestBed
exactly works. I don't see why does it prevent you from installing a mock before the getCustomer
call is made. You should use a framework that lets you do so.
But it is possible to do with the current setup: just postpone awaiting on the promise!
httpMock = TestBed.get(HttpTestingController);
let customerPromise = service.getCustomer(id);
let request = httpMock.expectOne('http://myurl.com');
let actual = await customerPromise;
Upvotes: 5