React Jest如何测试一个外部异步等待函数被调用?

问题描述 投票:0回答:1

我有一个react hook组件和onClick事件,当我触发该事件时,我会从其他文件模块中调用一个异步函数,我怎么能用Jest测试这个方法被调用,因为这个方法不是通过prop而是从外部资源中传递的,例如

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

我试着在我的测试中使用jest.fn或jest.spy,但似乎不起作用。

import * as externalMod from '../../../externalFile';
it('someAsyncFn should called', async() => {
   const spy = spy(externalMod, 'someAsyncFn');
   ...simulate('click');
   await expect(spy).toHaveBeenCalled();
})
reactjs async-await jestjs enzyme
1个回答
1
投票

你可以用 jest.mock:

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

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

it('someAsyncFn should called', async() => {
   someAsyncFn.mockResolvedValue(someDataToMock);
   ...simulate('click');
   expect(someAsyncFn).toHaveBeenCalled();
})
© www.soinside.com 2019 - 2024. All rights reserved.