【发布时间】:2021-09-03 08:11:30
【问题描述】:
我有一个简单的 404 组件,它将更改 window.location 以将“/404”添加到当前位置。
const My404 = () => {
const location = useLocation();
useEffect(() => {
window.location.replace(`/404${location.pathname}`);
}, []);
...
我正在尝试使用 React 测试库对此进行测试,但我似乎无法让它看到变化,即使在使用 await waitFor...
it('Should add /404 to start of pathname', async () => {
const history = createMemoryHistory()
history.push('/some-route')
const rendered = render(
<Router history={history}>
<My404 />
</Router>
);
await waitFor(() => expect(window.location.pathname).toBe('/404/some-route'));
});
测试失败:
Expected: "/404/some-route"
Received: "/"
更新
我只是通过在更改前后注销location 和window.location.pathname 进行了快速检查...
位置:
{ location:
{
pathname: '/some-route',
search: '',
hash: '',
key: '14xswz'
}
}
window.location.pathname:
/
【问题讨论】:
-
我认为你不应该使用
window.location.replace,而是使用useHistory 并调用history.replace()。 -
啊,是的!我知道我错过了一些东西。我确实最终让我的代码正常工作,所以我一定会添加一个封装这两条路线的答案。
标签: reactjs location window react-testing-library pathname