Jest测试环境下如何向React Native模态框传递useState参数?
问题原因
你收到Invalid hook call报错是因为useState属于React Hook,只能在React函数组件/自定义Hook的函数体顶层调用,直接在Jest测试用例的普通函数作用域内调用Hook不符合调用规则。
最佳实现方案
分两种常用场景选择即可:
方案1:用Jest模拟函数(单元测试首选)
绝大多数单元测试场景下,你只需要验证setModalVisible是否被正确触发,不需要真实的状态响应,直接传Jest模拟函数即可:
import { render, fireEvent } from '@testing-library/react'; // 你的其他导入 test('点击模态框关闭按钮触发隐藏回调', () => { // 创建模拟的set函数 const mockSetModalVisible = jest.fn(); const { getByRole } = render( <AuthProvider> <PDFViewer modalVisible={true} setModalVisible={mockSetModalVisible} file="" /> </AuthProvider> ); // 模拟点击关闭按钮 fireEvent.click(getByRole('button', { name: /关闭/i })); // 断言set函数被正确调用 expect(mockSetModalVisible).toHaveBeenCalledWith(false); });
方案2:包装测试父组件(需要真实状态联动时使用)
如果你需要测试模态框显示/隐藏的完整状态变化流程,可以在测试代码里声明一个临时的父组件,在父组件内部调用useState再传参给PDFViewer:
import { render, fireEvent } from '@testing-library/react'; import { useState } from 'react'; // 你的其他导入 test('模态框点击关闭后隐藏', () => { // 声明测试用父组件,在组件内部调用useState符合Hook规则 const TestPDFViewerWrapper = () => { const [modalVisible, setModalVisible] = useState(true); return ( <AuthProvider> <PDFViewer modalVisible={modalVisible} setModalVisible={setModalVisible} file="" /> </AuthProvider> ) }; const { queryByRole, getByRole } = render(<TestPDFViewerWrapper />); // 点击关闭按钮 fireEvent.click(getByRole('button', { name: /关闭/i })); // 断言模态框已从DOM中移除 expect(queryByRole('dialog')).not.toBeInTheDocument(); });
说明
两种方案都不会触发Hook调用报错,可根据你的测试需求选择:如果只是验证回调触发逻辑选方案1即可,代码更简洁性能更好;如果需要验证状态变化后的UI渲染效果选方案2。
内容的提问来源于stack exchange,提问作者tglover
相关产品推荐
相关产品推荐

