【问题标题】:Testing redirect after submit with React Testing Library使用 React 测试库提交后测试重定向
【发布时间】:2020-02-10 06:15:51
【问题描述】:

我正在尝试测试登录组件。特别是它在成功登录时重定向。手动测试时效果很好。但在我的测试中,它从不进行重定向,因此找不到“注销”链接:

test('successfully logs the in the user', async () => {
  const fakeUserResponse = {success: true, token: 'fake_user_token'}
  jest.spyOn(window, 'fetch').mockImplementationOnce(() => {
    return Promise.resolve({
      json: () => Promise.resolve(fakeUserResponse),
    })
  })
  const { getByText, getByLabelText, findByTestId } = render(<Router><Login /></Router>)

  fireEvent.change(getByLabelText(/email/i), {target: {value: 'dan@example.com'}})
  fireEvent.change(getByLabelText(/password/i), {target: {value: 'password1234'}})
  fireEvent.click(getByText(/submit/i))

  await waitForElement(() => getByText(/logout/i));
})

我正在使用react-router 版本 4 进行重定向,如下所示:

{state.resolved ? <Redirect to="/" /> : null}

我是不是走错路了?

【问题讨论】:

    标签: reactjs unit-testing jestjs react-router-v4 react-testing-library


    【解决方案1】:

    所以我最终这样做了:

    const { getByText, getByLabelText, } = render(
      <Router>
        <Login/>
        <Switch>
          <Route path="/">
            <div>logged out</div>
          </Route>
        </Switch>
      </Router>
    )
    
    fireEvent.change(getByLabelText(/email/i), {target: {value: 'dan@example.com'}})
    fireEvent.change(getByLabelText(/password/i), {target: {value: 'password1234'}})
    fireEvent.click(getByText(/submit/i))
    
    await waitForElement(() => getByText(/logged out/i))
    

    【讨论】:

      【解决方案2】:

      您可以模拟Redirect 组件的实现以显示一些包含路径的文本,而不是重定向到它:

      jest.mock('react-router-dom', () => {
        return {
          Redirect: jest.fn(({ to }) => `Redirected to ${to}`),
        };
      });
      

      并期望您的组件以正确的路径显示文本:

      expect(screen.getByText('Redirected to /')).toBeInTheDocument();
      

      【讨论】:

        【解决方案3】:

        我个人模拟了Redirect 组件使用的history.replace 函数。

        const history = createBrowserHistory();
        history.replace = jest.fn();
        
        render(
          <Router history={history} >
            <Component />
          </Router>
        );
        
        // trigger redirect
        
        expect(history.replace).toHaveBeenCalledWith(expect.objectContaining({
          "pathname": "/SamplePath",
          "search": "?SampleSearch",
          "state": { "Sample": "State" }
        }));
        

        这允许您检查的不仅仅是正确的路径。 请确保您在测试中使用Router 而不是BrowserRouter。后者不接受历史道具。

        【讨论】:

          猜你喜欢
          • 2021-07-03
          • 2020-08-28
          • 1970-01-01
          • 1970-01-01
          • 2020-03-24
          • 1970-01-01
          • 1970-01-01
          • 2019-02-20
          • 1970-01-01
          相关资源
          最近更新 更多