0

I have a function:

funtion foo() {
  Spinner.setVisible(true);
  await ApiService.doApiCall();
  Spinner.setVisible(false);
}

I'd like to unit test the order of function calls, to make sure the spinner is being shown before the API call and hidden afterwards.

I use Jest. I tried this:

import 'jest-extended';

describe('foo', () => {
  it('should make spinner visible before the api call', async () => {
    const setVisibleSpy = jest.spyOn(Spinner, 'setVisible').mockImplementation(() => true);
    const doApiCallSpy = jest.spyOn(ApiService, 'doApiCall').mockImplementation(() => Promise.resolve(true));
    expect(setVisibleSpy).toHaveBeenCalledBefore(doApiCallSpy ); // <-- THIS WORKS!!!
  })

  it('should make spinner hidden afterthe api call', async () => {
    const setVisibleSpy = jest.spyOn(Spinner, 'setVisible').mockImplementation(() => true);
    const doApiCallSpy = jest.spyOn(ApiService, 'doApiCall').mockImplementation(() => Promise.resolve(true));
    expect(setVisibleSpy).toHaveBeenCalledAfter(doApiCallSpy ); // <-- THIS DOESN'T WORK!!!
  })
})

As I understand, the check after doesn't work, because the very first call of the setVisible() function actually happen before the doApiCall().

How can I check that the second call of the setVisible() function happened after the doApiCall() call?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
eXception
  • 1,307
  • 1
  • 7
  • 22
  • Control when the promise resolves using the deferred pattern. That way you can assert that it was _last_ called with true before resolving and with false after resolving. – jonrsharpe Aug 20 '21 at 10:16
  • I thought about that, but feels a bit hacky. I expected something like accessing call order or maybe to check if `setVisibility` function was called with certain params alongside with the order check – eXception Aug 20 '21 at 12:28
  • 1
    You could write your own toHaveBeenNthCalledBefore/After matchers, based on the existing examples, or just assert on the mock properties they use (see links from e.g. https://stackoverflow.com/q/46066250/3001761). – jonrsharpe Aug 20 '21 at 12:32

0 Answers0