首页 > 解决方案 > 在测试中完成获取时的异步路径更新

问题描述

使用 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

知道如何等待获取失败并重定向吗?

标签: javascriptreactjsjestjsreact-testing-library

解决方案


你试过用wait吗?

await wait(() => expect(history.location.pathname).toBe('/error'))

推荐阅读