【发布时间】:2021-11-21 07:48:25
【问题描述】:
我正在尝试使用 useHistory 和 useLocation 为 React 组件编写测试,如下所示:
import { useHistory, useLocation } from 'react-router-dom';
export function MyComponent() {
let location = useLocation();
let history = useHistory();
function changeUrl(param) {
// some logic here
if(foo) {
history.push(location.pathname);
} else {
history.push(param)
}
}
return (<div>{/* actual elements here */}</div>)
}
这是测试文件:
import { render } from "@testing-library/react";
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: jest.fn().mockImplementation(() => ({ pathname: 'a' })),
useHistory: jest.fn().mockImplementation(() => ({ push: () => { } })),
}));
it('should do xxx', () => {
render(<MyComponent/>);
});
这会导致
Error: Uncaught [TypeError: Cannot read property 'pathname' of undefined]
错误来自location.pathname。同时,useHistory 不会抛出任何错误。
有人知道出了什么问题吗?任何建议将不胜感激。
附言
如果我像下面这样在it 中使用mockImplementation,则不会发生错误。
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: jest.fn().mockImplementation(() => ({ push: () => { } })),
}));
const { useLocation } = require('react-router-dom');
it('should do xxx', () => {
useLocation.mockImplementation(() => { pathname: 'a' });
render(<MyComponent/>);
});
我不明白为什么会发生这种情况......
【问题讨论】:
-
我可能遗漏了一部分,但那是什么? :
function changeUrl(location.pathname) { ... }?我从未见过像这样的函数声明,这里应该是一个参数,而不是要传递的变量。可以直接在函数内部检索location.pathname,为什么要这样? -
@RobinMichay 啊,对不起,这不是一个很好的例子。更新了