In Jest unit testing, when a component under test uses the useHistory hook from react-router-dom, we typically need to mock it to control and test routing-related logic. Below are the steps and examples for mocking useHistory:
Step 1: Setting up the Jest Test File
First, import the necessary modules and prepare your component in your Jest test file.
javascriptimport React from 'react'; import { render, fireEvent } from '@testing-library/react'; import { Router } from 'react-router-dom'; import { createMemoryHistory } from 'history'; import MyComponent from './MyComponent'; // Assume this is the component you're testing
Step 2: Mocking useHistory
Next, we use mock to simulate useHistory. There are two common approaches:
Method 1: Directly overriding useHistory in the test
You can directly override useHistory in your test file.
javascriptimport { useHistory } from 'react-router-dom'; jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useHistory: jest.fn(), }));
Then, in your specific test case, define how useHistory should behave:
javascripttest('should navigate to home page on button click', () => { const historyMock = { push: jest.fn(), location: {}, listen: jest.fn() }; useHistory.mockReturnValue(historyMock); const { getByText } = render(<MyComponent />); fireEvent.click(getByText('Go Home')); expect(historyMock.push).toHaveBeenCalledWith('/home'); });
Method 2: Using Router and createMemoryHistory
Another approach is to wrap your component with Router and createMemoryHistory to flexibly control routing state.
javascripttest('should navigate on button click', () => { const history = createMemoryHistory(); const { getByText } = render( <Router history={history}> <MyComponent /> </Router> ); fireEvent.click(getByText('Go Home')); expect(history.location.pathname).toBe('/home'); });
Step 3: Execution and Verification
Regardless of the method chosen, execute your test command to run the tests and verify expected behavior. Use npm test or your configured command to run Jest.
Summary
Mocking useHistory can be achieved by directly mocking useHistory or using Router and createMemoryHistory. The choice depends on personal or team preferences for testing strategies. If your component heavily relies on routing behavior, using Router and createMemoryHistory may be more appropriate.