乐闻世界logo
搜索文章和话题

How to mock useRef using jest.mock and react testing library

1个答案

1

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:

  1. Set up Jest mock: First, you need to set up the mock for useRef in your test file. This can be achieved using Jest's jest.mock function, which allows us to override the implementation of a module.

  2. Create a mock return value: useRef returns an object containing a property named current. We can create an object with a current property to mock the return value of useRef.

  3. Use the mock in tests: Apply the mocked useRef implementation 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.

javascript
import 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:

javascript
import 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).

2024年6月29日 12:07 回复

你的答案