【问题标题】:React testing library, how to test history.pushReact 测试库,如何测试 history.push
【发布时间】:2021-02-20 13:15:33
【问题描述】:

在 React 应用程序中,我有一个以编程方式转到新网址的按钮:

<ComposeButton
  onClick={() => {
    history.push('some-link'))
  }}
>

在我的测试中,我按照 React Router 的 react-testing-library 文档中的说明渲染我的组件:

const renderComponent = (page: Pages) => {
  const history = createMemoryHistory()

  return renderWithState(
    <MockedProvider
      mocks={mocks}
      addTypename={false}
      defaultOptions={{
        watchQuery: { fetchPolicy: 'no-cache' },
        query: { fetchPolicy: 'no-cache' }
      }}
    >
      <Router history={history}>
        <ComponentToRender />
      </Router>
    </MockedProvider>
  )
}

如何在 react-testing-library 中等待这个更改页面?

it('sends invitations', async () => {
    const { getByTestId, queryByTestId, debug, getByText } = renderComponent(
      Pages.contacts
    )

    await new Promise((resolve) => setTimeout(resolve))

    const writeMessageBtn = getByTestId('write-message-btn')
    waitFor(() => fireEvent.click(writeMessageBtn))
    await new Promise((resolve) => setTimeout(resolve))

    waitFor(() => debug()) // <- expect to see new page

    getByText('EV_305_NEW_INVITATION_SEND') // <- this is in the second page, never get here
})

使用debug时,我永远看不到新页面的内容(点击按钮后)

【问题讨论】:

  • 您是否在 Router 内的测试中渲染您的组件,并为“some-link”定义了路由?
  • 我在测试中添加了Router,但仍然测试不等待新的页面内容。

标签: reactjs jestjs react-testing-library


【解决方案1】:

我不确定这是否会使一切正常,但我可以强调一下您分享的代码示例存在一些问题:

  1. 您正在渲染Router,但没有渲染Routes。请改用MemoryRouter 并提供与您的实际应用程序相同的路由 - 至少提供您要推送到历史记录中的路由

  2. 您没有正确使用react-testing-library。不要使用getByTestId,而是使用findByTestId。例如const writeMessageBtn = await findByTestId('write-message-btn')。区别在于get* 查询是同步的,而find* 是异步的。您无需等待任意超时,测试库将尝试查找元素几秒钟。 这同样适用于您使用get*的其他地方

【讨论】:

  • 您能解释一下为什么不使用 get* 吗?
  • @BastianStein 我稍微扩展了我的答案,有关更多详细信息,我建议您阅读react-testing-library的文档
  • 我知道 get 是同步的。在测试中,我为什么要使用异步版本,无论如何我都在等待结果?
  • 该测试可能会导致您想要等待的 UI 发生变化。最好等待 UI 更改而不是超时或承诺,因为这些可能会在 UI 有机会更新之前结束
  • 我现在明白了,谢谢。我有一个误解,认为 get 会阻塞一段时间,直到它可以找到元素,或者失败。但事实并非如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 2023-02-09
  • 2019-04-22
  • 1970-01-01
  • 2019-04-07
  • 2021-07-03
相关资源
最近更新 更多