使用React Testing Library提交后进行测试重定向

时间:2019-10-13 11:04:28

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

我正在尝试测试登录组件。具体来说,它会在成功登录后重定向。手动测试时效果很好。但是在我的测试中,它从不执行重定向,因此无法找到“注销”链接:

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}

我会以错误的方式处理吗?

2 个答案:

答案 0 :(得分:0)

所以我最终这样做了:

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))

答案 1 :(得分:0)

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

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

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

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