在测试中完成提取时的异步路径更新
Asynchronous path update when a fetch is done in a test
使用 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');
});
});
错误 'when signup for encounters an error it redirects to error page':
Expected: "/error"
Received: "/signup"
上面使用的 renderWithRouter 方法来自源:https://testing-library.com/docs/example-react-router
知道如何等待提取失败并重定向吗?
您尝试过使用 wait
吗?
await wait(() => expect(history.location.pathname).toBe('/error'))
使用 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');
});
});
错误 'when signup for encounters an error it redirects to error page':
Expected: "/error"
Received: "/signup"
上面使用的 renderWithRouter 方法来自源:https://testing-library.com/docs/example-react-router
知道如何等待提取失败并重定向吗?
您尝试过使用 wait
吗?
await wait(() => expect(history.location.pathname).toBe('/error'))