Jest+Enzyme测试React表单报Cannot read property 'value'错误如何解决
报错原因
- 执行
simulate('submit')模拟表单提交时没有传入符合预期的事件对象,导致组件内部读取event.target.location时返回undefined,调用value属性就抛出了类型错误。 - 你的测试代码中单独声明的
onPostJobSubmitmock函数和组件内部的提交逻辑没有任何关联,且函数式组件不支持通过wrapper.instance()获取实例调用内部方法,该断言逻辑本身无法通过。 - 未mock Redux的
useDispatch方法,也会导致后续提交逻辑的断言无法正常执行。
修复方案
1. 直接修复现有测试逻辑
补充模拟事件对象,mock useDispatch来验证提交行为即可,示例代码如下:
import { useDispatch } from 'react-redux'; import { postJobAction } from './redux/postJobActions'; // 全局mock redux的useDispatch方法 jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useDispatch: jest.fn() })); it('should submit job post form on save button click', () => { const mockDispatch = jest.fn(); useDispatch.mockReturnValue(mockDispatch); // 模拟提交时传入完整的事件对象 wrapper.find('form').simulate('submit', { preventDefault: jest.fn(), target: { title: { value: '前端开发工程师' }, location: { value: '上海' } } }); // 验证dispatch被正确调用,传入参数符合预期 expect(mockDispatch).toHaveBeenCalledWith(postJobAction({ title: '前端开发工程师', location: '上海' })); });
2. 可选优化(更符合React最佳实践)
将表单改为受控组件,用state托管输入值,避免直接操作原生form的target属性,后续测试逻辑也更贴合实际用户操作:
组件代码调整
import React, { useState } from 'react'; import { useDispatch } from 'react-redux'; import { postJobAction } from './redux/postJobActions'; const PostJobComponent = () => { const dispatch = useDispatch(); const [formState, setFormState] = useState({ title: '', location: '' }); const handleInputChange = (e) => { const { name, value } = e.target; setFormState(prev => ({ ...prev, [name]: value })); }; const onPostJobSubmit = (event) => { event.preventDefault(); dispatch(postJobAction(formState)); }; return ( <div className='post-job'> <form onSubmit={onPostJobSubmit}> <div> <label>职位名称</label> <input type='text' name='title' value={formState.title} onChange={handleInputChange} className='job__title' placeholder='例如:前端开发、项目经理等' /> </div> <div> <label>工作地点</label> <input type='text' name='location' value={formState.location} onChange={handleInputChange} className='job__location' placeholder='例如:德国柏林' /> </div> <div> <button>保存</button> </div> </form> </div> ); }; export default PostJobComponent;
对应测试代码
import { useDispatch } from 'react-redux'; import { postJobAction } from './redux/postJobActions'; jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useDispatch: jest.fn() })); it('should submit job post form on save button click', () => { const mockDispatch = jest.fn(); useDispatch.mockReturnValue(mockDispatch); // 模拟用户输入行为 wrapper.find('input[name="title"]').simulate('change', { target: { name: 'title', value: '产品经理' } }); wrapper.find('input[name="location"]').simulate('change', { target: { name: 'location', value: '深圳' } }); // 提交表单 wrapper.find('form').simulate('submit', { preventDefault: jest.fn() }); expect(mockDispatch).toHaveBeenCalledWith(postJobAction({ title: '产品经理', location: '深圳' })); });
内容的提问来源于stack exchange,提问作者Om3ga
相关产品推荐
相关产品推荐

