When using Jest for unit testing in React, we often need to mock various built-in hooks, such as useRef. useRef is typically used to hold references to DOM elements within functional components or to store data that persists across rendering cycles.
Steps to Mock useRef:
-
Set up Jest mock: First, you need to set up the mock for
useRefin your test file. This can be achieved using Jest'sjest.mockfunction, which allows us to override the implementation of a module. -
Create a mock return value:
useRefreturns an object containing a property namedcurrent. We can create an object with acurrentproperty to mock the return value ofuseRef. -
Use the mock in tests: Apply the mocked
useRefimplementation to your component and verify its behavior in the test.
Example Code
Suppose we have a React component that uses useRef to access a button element and focuses it on component mount.
javascriptimport React, { useEffect, useRef } from 'react'; function FocusButton() { const buttonRef = useRef(null); useEffect(() => { buttonRef.current.focus(); }, []); return <button ref={buttonRef}>Click me!</button>; }
Now, we need to test that this component focuses the button on mount. Here's how to set up the test and mock useRef:
javascriptimport React from 'react'; import { render } from '@testing-library/react'; import FocusButton from './FocusButton'; // Mock useRef jest.mock('react', () => ({ ...jest.requireActual('react'), useRef: jest.fn(), })); describe('FocusButton component', () => { it('focuses the button on mount', () => { const mockRef = { current: { focus: jest.fn() } }; React.useRef.mockReturnValue(mockRef); render(<FocusButton />); expect(mockRef.current.focus).toHaveBeenCalled(); }); });
Explanation
In this test, we first mock the React useRef hook using jest.mock. We create an object with a current property that has a focus method and return it in the mock. When the FocusButton component renders, it attempts to call buttonRef.current.focus(). Our test verifies that the focus method is called, confirming that the component behaves as expected. By doing this, we can ensure that the component's logic works correctly even in environments without DOM (such as Jest).