I have a function with chained api calls. I have added rxjs delay
between two API calls.
How to write test case in Jest to handle delay
between two API calls.
Sequence of APIs
- first API call
- after
switchMap
calldelay
of5000
. - Call Next API
switchMap
further conditional code to check conditions
You need Timer Mocks.
https://testing-library.com/docs/using-fake-timers/
https://jestjs.io/docs/timer-mocks
example:
describe('Test', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.runOnlyPendingTimers();
jest.useRealTimers();
});
test('should add a message', () => {
messageService.add(message);
jest.runOnlyPendingTimers();
expect(spy).toHaveBeenCalled();
});
});
Please don’t just dump all your code. Make an effort in removing the parts that are not essential to the question. If possible, create a minimal repro on Stackblitz. Keep in mind that if you don’t make that effort initially, every person reading your question will have to make that effort for you, decreasing your chances to get an answer.
You have to use a combination of
fakeAsync
andtick
to be able to handle thedelay
of 1 second. Here are two examples: baldur.gitbook.io/angular/angular-test/testing/… and medium.com/@penghuili/….