React组件Mock置于beforeEach中时Mock函数未被调用的问题求助
React组件Mock置于beforeEach中时Mock函数未被调用的问题求助
大家好,我现在遇到一个React组件测试的问题,想请教一下各位:
我正在尝试Mock一个React函数组件,以此验证父组件传递给它的属性是否正确。当我把jest.mock放在文件最顶部时,测试运行完全正常,代码示例如下:
const mockTrackList = jest.fn(); jest.mock('../components/Tracklist/VirtualTracklist', () => (props: TrackListProps) => { mockTrackList(props); return <div /> }); describe('Test the RequestList component', () => { it('test-title', async () => { flushSync(() => { render( <RequestList streamer={'streamer'} isStreamer={false} /> ); }) await waitFor(async () => { expect(mockTrackList).toHaveBeenLastCalledWith([...]); }); }); });
但当我把Mock逻辑调整到beforeEach钩子中,用单独定义的组件函数返回时,mockTrackList完全没有被调用,直接导致测试失败。调整后的代码如下:
const mockTrackList = jest.fn(); const mockComp = (props: TrackListProps) => { mockTrackList(props); return <div /> }; describe('Test the RequestList component', () => { beforeEach(() => { jest.mock('../components/Tracklist/VirtualTracklist', () => mockComp); }); it('test-title', async () => { flushSync(() => { render( <RequestList streamer={'streamer'} isStreamer={false} /> ); }) await waitFor(async () => { expect(mockTrackList).toHaveBeenLastCalledWith([...]); }); }); });
我实在搞不懂为什么两种写法差异这么大,明明逻辑一致,只是把jest.mock移到了beforeEach里。有没有大佬能解释下原因,或者告诉我怎么调整才能让第二种写法正常工作呢?
备注:内容来源于stack exchange,提问作者matthesinator
相关产品推荐
相关产品推荐

