React测试问题:多次jest.mock自定义Hook返回值未更新怎么办?
问题原因及解决方案
核心问题
jest.mock 是模块级别的模拟,它会在测试文件的所有代码执行前就被Jest处理。你在每个测试用例内重复写 jest.mock 的方式不会生效——第一个mock定义会被优先加载并一直沿用,后续的mock无法覆盖它。另外,jest.restoreAllMocks() 仅用于恢复由 jest.spyOn 创建的mock的原始实现,对模块级别的mock无效。
正确实现方式
- 在文件顶部统一mock模块,将Hook设为可修改的mock函数
jest.mock('components/section/hooks/use-sections-overview', () => ({ useSectionsOverview: jest.fn(), }));
- 在每个测试用例中单独设置Hook的返回值
- 无内容渲染测试:
test('组件无内容渲染', () => { const { useSectionsOverview } = require('components/section/hooks/use-sections-overview'); // 设置mock返回空数组 useSectionsOverview.mockReturnValue({ sections: [] }); // 渲染组件并执行断言逻辑 // render(<YourComponent />); // expect(screen.queryByRole('list')).not.toBeInTheDocument(); });
- 渲染内容测试:
test('组件渲染内容', () => { const { useSectionsOverview } = require('components/section/hooks/use-sections-overview'); // 设置mock返回测试数据 useSectionsOverview.mockReturnValue({ sections: [{id: '1', content: 'test'}] }); // 渲染组件并执行断言逻辑 // render(<YourComponent />); // expect(screen.getByText('test')).toBeInTheDocument(); });
- 在afterEach中清除mock状态
afterEach(() => { // 清除mock的调用记录和返回值,避免测试用例间互相影响 jest.clearAllMocks(); });
内容的提问来源于stack exchange,提问作者Pierre Olivier Tran
相关产品推荐
相关产品推荐

