测试接收React.useRef参数的函数时如何mock useRef以支持removeChild操作
问题根因
- 首次报错
removeChild is not a function是因为构造的mock ref对象的current属性缺少removeChild方法,和入参是不是真的useRef返回值无关,只要对象结构符合要求即可。 - 调整后报错
Cannot read property 'children' of undefined是因为入参类型传错:postData要求的入参是React.useRef()的返回值(即带current属性的ref对象),你把mock后的useRef钩子函数本身传入了,函数内部读取useRef.current时得到undefined,后续读取children自然报错。
解决方案
不需要mock整个React的useRef钩子,直接构造符合接口要求的ref对象,补充对应的removeChildmock实现即可:
it('should work', () => { // 单独维护children数组,方便removeChild操作修改 const mockChildren = [ { value: '' }, { value: '' } ]; const formRef = { current: { action: '', submit: jest.fn(), children: mockChildren, // 实现removeChild的mock逻辑 removeChild: jest.fn((child) => { const targetIndex = mockChildren.indexOf(child); if (targetIndex > -1) { mockChildren.splice(targetIndex, 1); } }) } }; // 直接传入构造好的ref对象即可 postData(formRef, 'mock_token', 'mock_id'); // 可选:添加断言验证逻辑正确性 expect(formRef.current.children[0].value).toBe('mock_token'); expect(formRef.current.children[1].value).toBe('mock_id'); expect(formRef.current.removeChild).not.toHaveBeenCalled(); });
如果需要验证删除逻辑,只需调整传参即可,比如传入空id:
it('should remove child with empty value', () => { const mockChildren = [ { value: '' }, { value: '' } ]; const formRef = { current: { action: '', submit: jest.fn(), children: mockChildren, removeChild: jest.fn((child) => { const targetIndex = mockChildren.indexOf(child); if (targetIndex > -1) { mockChildren.splice(targetIndex, 1); } }) } }; postData(formRef, 'mock_token', ''); expect(formRef.current.removeChild).toHaveBeenCalledTimes(1); expect(formRef.current.children.length).toBe(1); });
内容的提问来源于stack exchange,提问作者stacky
相关产品推荐
相关产品推荐

