使用react testing library,我想测试如果回迁产生错误,应用程序是否重定向到错误页。
我的应用程序成功地做到了这一点。然而,它在测试中不起作用。可能是因为提取是异步完成的。
describe("<SignUp /> routing", () => {
it('navigates to signup page', () => {
const { getByTestId, history } = renderWithRouter(<App />);
expect(history.location.pathname).toBe('/');
const headerSignUpLink = getByTestId("nav-header-signup");
fireEvent.click(headerSignUpLink);
// this works fine
expect(history.location.pathname).toBe('/signup');
}
it('when signup for encounters an error it redirects to error page', async () => {
const { getByTestId, history } = renderWithRouter(
<App />, { route: '/signup' }
);
// all good
expect(history.location.pathname).toBe('/signup');
const formSignUpButton = getByTestId("button-submit");
// this click fires an asynchronous fetch
fireEvent.click(formSignUpButton);
// The fetch fails on purpose. Now the app should be redirected to an error page. In my browser this works fine. However in the test it doesn't
// Now this is where the test fails. The path is not seen as updated:
expect(history.location.pathname).toBe('/error');
});
});
误差在
'当注册遇到错误时,它会重定向到错误页'
:
Expected: "/error"
Received: "/signup"
上面使用的renderWithRouter方法来自源代码:
https://testing-library.com/docs/example-react-router
知道如何等待获取失败并重定向吗?