0
votes

I have an react hook component and onClick event, when I trigger the event I would call an async function from other file/module, how could I test this method being called with Jest since this method is not passing through prop but from external resource, for example

import {someAsyncFn} from '../../../externalFile';
--My component on click method
const onClick = async (userId) => {
    await someAsyncFn(userId);
};

I tried to use jest.fn or jest.spy in my test but that doesn't seem to work..

import * as externalMod from '../../../externalFile';
it('someAsyncFn should called', async() => {
   const spy = spy(externalMod, 'someAsyncFn');
   ...simulate('click');
   await expect(spy).toHaveBeenCalled();
})
1

1 Answers

1
votes

You can do that with jest.mock:

import {someAsyncFn} from '../../../externalFile';

jest.mock('../../../externalFile');

it('someAsyncFn should called', async() => {
   someAsyncFn.mockResolvedValue(someDataToMock);
   ...simulate('click');
   expect(someAsyncFn).toHaveBeenCalled();
})