typescript 当mock不在文件顶部时,不调用Mock函数

6rqinv9w  于 2023-05-01  发布在  TypeScript
关注(0)|答案(1)|浏览(154)

我试图模拟一个React函数组件来验证传递给它的属性。当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([...]);
        });
    });
});

但是,当这样做时,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([...]);
        });
    });
});
nsc4cvqm

nsc4cvqm1#

正如jonrsharpe所建议的,推迟模块导入解决了我的问题。以下是更新后的beforeEach:

let RequestList: FC<RequestListProps>;
    beforeEach(async () => {
        jest.mock('../components/Tracklist/VirtualTracklist', () => mockComp);
        RequestList = (await import('../components/RequestList')).default;
    });

相关问题