How to mock history.push with the new React Router Hooks using Jest
·
Answer a question
I am trying to mock history.push inside the new useHistory hook on react-router and using @testing-library/react. I just mocked the module like the first answer here: How to test components using new react router hooks?
So I am doing:
//NotFound.js
import * as React from 'react';
import { useHistory } from 'react-router-dom';
const RouteNotFound = () => {
const history = useHistory();
return (
<div>
<button onClick={() => history.push('/help')} />
</div>
);
};
export default RouteNotFound;
//NotFound.test.js
describe('RouteNotFound', () => {
it('Redirects to correct URL on click', () => {
const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
const { getByRole } = render(
<MemoryRouter>
<RouteNotFound />
</MemoryRouter>
);
fireEvent.click(getByRole('button'));
expect(mockHistoryPush).toHaveBeenCalledWith('/help');
});
})
But mockHistoryPush is not called... What am I doing wrong?
Answers
You actually do not need to mock react-router-dom (at least for v5) as it provides a bunch of testing tools: https://v5.reactrouter.com/web/guides/testing
To check your history is actually changed, you can use createMemoryHistory and inspect its content:
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Menu } from './Menu';
import { createMemoryHistory } from 'history'
import { Router } from 'react-router-dom';
test('triggers path change', () => {
const history = createMemoryHistory();
render(
<Router history={history}>
<Menu />
</Router>
);
const aboutItem = screen.getByText('About');
expect(aboutItem).toBeInTheDocument();
userEvent.click(aboutItem);
expect(history.length).toBe(2);
expect(history.location.pathname).toBe('/about');
});
更多推荐
所有评论(0)