使用React Testing Library的fireEvent触发输入框报错问题
问题原因及解决方案
问题根源
测试时直接渲染<SearchBar />,但组件必须接收setSearch作为props,触发onChange时会调用这个未传入的函数,导致报错。移除onChange后,不会调用这个不存在的函数,测试自然能通过。
解决方法
方式一:传入空函数作为setSearch props
修改测试代码,给SearchBar传递一个空函数即可避免报错:
test('Check SearchBar functionality', async () => { render(<SearchBar setSearch={() => {}} />); const textInput = screen.getByTestId('text-input'); fireEvent.change(textInput, { target: { value: 'mens cotton jacket' } }); });
方式二:Mock函数并验证调用逻辑
如果需要验证setSearch是否被正确触发,用jest mock函数来做断言:
test('Check SearchBar functionality', async () => { const mockSetSearch = jest.fn(); render(<SearchBar setSearch={mockSetSearch} />); const textInput = screen.getByTestId('text-input'); fireEvent.change(textInput, { target: { value: 'mens cotton jacket' } }); // 验证函数是否按预期调用 expect(mockSetSearch).toHaveBeenCalledWith('mens cotton jacket'); });
额外优化建议
React Testing Library官方更推荐用userEvent替代fireEvent,它能模拟更贴近真实用户的交互行为:
import { userEvent } from '@testing-library/user-event'; test('Check SearchBar functionality', async () => { const mockSetSearch = jest.fn(); render(<SearchBar setSearch={mockSetSearch} />); const user = userEvent.setup(); const textInput = screen.getByTestId('text-input'); await user.type(textInput, 'mens cotton jacket'); expect(mockSetSearch).toHaveBeenCalledWith('mens cotton jacket'); });
内容的提问来源于stack exchange,提问作者Kosh
相关产品推荐
相关产品推荐

