我正在尝试模拟 history.push
在新的 useHistory
挂钩 react-router
并使用 @testing-library/react
。我只是像这里的第一个答案一样嘲笑模块: 如何使用新的反应路由器钩子测试组件?
所以我在做:
//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');
});
})
但是 mockHistoryPush
没有被调用……我做错了什么?
原文由 Albert Alises 发布,翻译遵循 CC BY-SA 4.0 许可协议
您实际上不需要模拟
react-router-dom
(至少对于v5),因为它提供了一堆测试工具: https ://v5.reactrouter.com/web/guides/testing要检查您的历史记录是否实际更改,您可以使用
createMemoryHistory
并检查其内容: