React/Jest测试中如何使用useRef?组件引用校验方法
测试中使用useRef报错,如何验证组件是否正确设置引用?
我在测试中尝试直接使用useRef,代码如下:
test('foo', () => { const myRef = useRef<HTMLInputElement | null>(null); render(<MyComponent inputRef={myRef} />); expect(myRef.current?.value).toBe('bar'); });
运行后触发错误:
TypeError: Cannot read properties of null (reading 'useRef')
我的目标是检查组件是否正确设置了引用,请问如何在测试中使用useRef?或者有无替代方案?
问题原因
useRef是React Hook,只能在React组件或自定义Hook的顶层作用域调用,测试函数不属于React渲染上下文,直接调用必然报错。
解决办法
方案1:用普通对象模拟Ref(最简单)
不需要用useRef,直接创建一个带current属性的普通对象,React会自动把对应的DOM元素赋值给这个属性:
test('foo', () => { const myRef = { current: null as HTMLInputElement | null }; render(<MyComponent inputRef={myRef} />); expect(myRef.current?.value).toBe('bar'); });
方案2:在测试用的临时组件里用useRef
如果一定要用useRef,可以在测试中渲染一个临时React组件,在组件内部调用useRef再传递给目标组件:
test('foo', () => { let inputRef: React.RefObject<HTMLInputElement> | null = null; render(() => { inputRef = useRef<HTMLInputElement | null>(null); return <MyComponent inputRef={inputRef} />; }); expect(inputRef?.current?.value).toBe('bar'); });
方案3:直接查询DOM元素(推荐)
如果你的核心需求是验证组件的DOM状态(比如输入框值),完全可以跳过ref,用测试库的查询方法直接获取元素,这更符合React测试的最佳实践:
import { screen } from '@testing-library/react'; test('foo', () => { render(<MyComponent />); // 根据角色、占位符、标签名等查询元素 const inputElement = screen.getByRole('textbox'); expect(inputElement).toHaveValue('bar'); });
内容的提问来源于stack exchange,提问作者DarkTrick
相关产品推荐
相关产品推荐

