1

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 Answer 1

2

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();
})
Sign up to request clarification or add additional context in comments.

10 Comments

I am a little confused, what's the usage of jest.mock of my external file while the actual method was imported already?
I've tried this, yes my someAsyncFn was being called, however it seems it never gets resolved, I have some other method after someAsyncFn are not being called that may be blocked by someAsyncFn, do you have any suggestion how to resolve that?
I've figured it out, seems I need to add await Promise.resolve(); after the expect(someAsyncFn).toHaveBeenCalled(); and it'll work
answer to your first question: it's how jest works internally. It parses your file, find jest.mock and processes it before parsing everything else(so import also comes next). That's why we mock and import and everything works well.
Thank you! One more question, seems like using the mock, my function is like fake one...so I'm expecting my function to be called with userId 1, but even I test it to have been called with userid 3 or even on parameter, test case also passed... does it mean after mock, all method inside my file are not real?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.