代码之家  ›  专栏  ›  技术社区  ›  Remi

在测试中完成提取时异步路径更新

  •  0
  • Remi  · 技术社区  · 5 年前

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

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

    1 回复  |  直到 5 年前
        1
  •  1
  •   Gio Polvara    5 年前

    你试过用 wait ?

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