javascript - 在测试中完成获取时的异步路径更新
问题描述
使用 react-testing-library 我想测试应用程序是否会在 fetch 产生错误时重定向到错误页面。
我的应用程序成功地做到了。但是,它在测试中不起作用。也许是因为获取是异步完成的。
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
知道如何等待获取失败并重定向吗?
解决方案
你试过用wait
吗?
await wait(() => expect(history.location.pathname).toBe('/error'))
推荐阅读
- c# - 如何在 .Net Core 项目中使用 WcfCoreMtomEncoder?
- linux - 以编程方式在 Gnome/Wayland 中制作终端窗口的屏幕截图
- c++ - Boost asio io_content 非阻塞运行
- javascript - Firefox 扩展 - 使用 onBeforeRequest 过滤和修改 HTTP POST 数据
- git - GitHub/GitLab REST API - 将分支直接合并到 Master
- c# - 在 c++ 中调用 c# 可执行文件托管并异步运行
- excel - EXCEL - 当数据透视图没有行字段时数据透视图时间序列
- gem5 - 问题是关于运行基准和老化 gem5
- tensorflow - 在 cpu 而不是 gpu 上使用带有 nvidia tensorrt 的 .h5 模型
- vb.net - 动态获取控件的名称和属性