问题出现的原因是在测试中使用了React Router的高阶组件withRouter,这会使测试中的组件被重新渲染,而在重定向之后重新加载,从而导致了循环调用。
解决方法是使用MemoryRouter而非withRouter作为测试中的路由组件。若需要使用保护路由组件,则需要使用render方法并手动生成location对象,代码如下:
import { MemoryRouter, Route } from 'react-router-dom';
...
test('protected route', () => {
const user = { username: 'testUser', password: 'testPassword' };
localStorage.setItem('user', JSON.stringify(user));
const location = { pathname: '/protectedRoute' };
render(
} />
);
expect(screen.getByTestId('protectedRoute')).toBeInTheDocument();
});
这里除了使用MemoryRouter之外,我们还手动生成了location对象,以确保在路由组件页面重新渲染时仍能正确显示页面。
上一篇:保护路由检查用户API