Is there a way to test http timeout behaviour of a service?
I'm using MockBackend even when setting job's timeout to 0 no logging of 'TIMEOUT' present.
export class MyHttpService {
private sendGetRequest (job: HttpJob): Observable<any> {
return this.http.get(job.getUrl(), this.options)
.share()
.timeout(job.getTimeout(), () => this.requestTimeout(job))
.catch((err) => this.errorHandler(err, job));
};
private requestTimeout(job: HttpJob): Error {
job.errorCode = ErrorCode.TIMEOUT;
console.log('TIMEOUT');
return new Error('timeout');
}
...
test (nothing is logged)
it('should resolve to TIMEOUT', () => {
job.timeout = 0;
let response: any;
service.sendRequest(job).subscribe(
(res: Response) => {
response = res.json();
console.log('OK', res);
},
err => {
response = err;
console.log('ER', err);
}
);
expect(job.errorCode).toEqual(ErrorCode.TIMEOUT);
});
Thx!
update: minimal example, if timeout is uncommented, it will fail
It's because the resolution of the
subscribe
method is asynchronous. You are trying to test synchronously.Here, he expectation happens synchronously before any asynchronous tasks triggered by the subscription. And the test completes synchronously even before the asynchronous tasks are complete (that's why you never see the console.log)
What you need to do is either use
async
and do the expectation in the subscription callbackOr use
fakeAsync
and force a fake synchronous resolution by callingtick