How to write test case in Jest to handle rxjs ‘delay’ between two API calls

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

  1. first API call
  2. after switchMap call delay of 5000.
  3. Call Next API
  4. switchMap further conditional code to check conditions

  • 1

    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 and tick to be able to handle the delay of 1 second. Here are two examples: baldur.gitbook.io/angular/angular-test/testing/… and medium.com/@penghuili/….

    – 

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();
  });
});

Leave a Comment