Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest check when async function gets called

I'm trying to test whether an async function (fire and forget) gets called.

Content.js

  export async function fireAndForgetFunction() {
    ...  
  }

  export async function getData() {
    ...
    fireAndForgetFunction()
    return true;
  }

I would like to test if fireAndForgetFunction has been called more than once.

Current test

  import * as ContentFetch from '../Content';

  const { getData } = ContentFetch;
  const { fireAndForgetFunction } = ContentFetch;

  it('test',async () => {
    const spy = jest.spyOn(ContentFetch, 'fireAndForgetFunction');

    await getData();

    expect(spy).toHaveBeenCalled();
  })

The test result to an error saying

    Expected number of calls: >= 1
    Received number of calls:    0

How could I do this test?

like image 395
Leonardo Drici Avatar asked Apr 22 '26 20:04

Leonardo Drici


1 Answers

If you don't want to await for fireAndForgetFunction in getData(), which I assume is the case, then providing a mock implementation of fireAndForgetFunction when creating the spy is your best option:

it('test', (done) => {
    const spy = jest.spyOn(ContentFetch, 'fireAndForgetFunction')
        .mockImplementation(() => {
          expect(spy).toHaveBeenCalled();
          done();
        })
    getData();
})
like image 180
mtkopone Avatar answered Apr 25 '26 09:04

mtkopone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!