I'm trying to use useRef in a test like this:
test('foo', () => {
const myRef = useRef<HTMLInputElement | null>(null);
render(<MyComponent inputRef={myRef} />);
expect(myRef.current?.value).toBe('bar');
});
However, this will give the following error:
TypeError: Cannot read properties of null (reading 'useRef')
Goal: I'd like to check, if the component sets the reference properly.
Question:
How can I use useRef
in my test? Or is there any workaround?
CodePudding user response:
You can call react hooks only in Components or in custom hooks. In order to use it in your tests you need to mock useRef or pass plain mock ref object to your component.
Here is the approach with mocked ref object:
const myMockRef: {current: HTMLInputElement | null} = {current: null}