Reputation: 1391
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
Upvotes: 1
Views: 2151
Reputation: 209072
It's because the resolution of the subscribe
method is asynchronous. You are trying to test synchronously.
it('..', () => {
doSomthing().subscribe(() => {
})
expect(something)
})
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 callback
import { async } from '@angular/core/testing'
it('..', async(() => {
doSomthing().subscribe(() => {
expect(something)
})
}))
Or use fakeAsync
and force a fake synchronous resolution by calling tick
import { fakeAsync, tick } from '@angular/core/testing'
it('..', fakeAsync(() => {
doSomthing().subscribe(() => {
// this is called when you tick
})
tick();
expect(something);
}))
Upvotes: 1