【问题标题】:@testing-library/react (rtl) 'waitFor' makes only success without await keyword@testing-library/react (rtl) 'waitFor' 只有在没有 await 关键字的情况下才会成功
【发布时间】:2023-03-12 00:47:01
【问题描述】:

await waitFor() 使我的测试失败,但waitFor() 使我的测试成功(无需等待)。

官方文档说

异步方法返回一个 Promise,因此在调用它们时必须始终使用 await 或 .then(done)。 (https://testing-library.com/docs/guide-disappearance)

我不知道如何正确测试。 我必须使用rerender吗?

it('toggles active status', async () => {
  render(<List {...listProps} />);
  const targetItem = screen.getByRole('heading', { name: /first/i });

  // de-active color is GRAY2, active color is MINT
  expect(targetItem).toHaveStyle({ color: GRAY2 });

  // click to change the color of targetItem
  // it dispatch action that update listProps
  // So changing listProps makes <List /> re-rendering
  fireEvent.click(targetItem);

  await waitFor(() => {
    // It throws an error because the color is still GRAY2 in jest runner.
    // But, in chrome browser, it's color MINT.
    expect(targetItem).toHaveStyle({ color: MINT }); // fail
  });

  // If not use 'await' keyword, this works well.
  // jest runner knows the color is MINT
  waitFor(() => {
    expect(targetItem).toHaveStyle({ color: MINT });
  });
});

【问题讨论】:

  • 我认为问题在于调度操作。使用重新渲染而不是 waitFor() 的新方法取得了成功。我猜想通过更改 props 重新渲染 DOM 的结果与组件测试无关。这样对吗?与否
  • 正如文档所说,对于waitFor,您应该始终使用await。如果您不使用await,那么测试通过的事实是因为断言expect(targetItem).toHaveStyle({ color: MINT }); 不会发生。确保您正在测试正确的行为。
  • @juliomalves 是的,你是对的。由于评论字符串长度的限制,我写了答案。

标签: javascript reactjs typescript react-testing-library


【解决方案1】:

如果我使用 waitFor() 而不使用 await 它不会失败,但也不是真正的成功。

期望语句在没有测试的情况下通过。 waitFor() 没有等待是我的误解。即使失败了也总是成功的。

最后,我知道测试框架无法检测到更改道具的结果。 props 是从父组件传递的,即使它实际上在 redux 存储中。

总之,我想测试子组件。 它从 Parent Component 获取 props,Parent 获取数据以从 redux store 传递 props。

Child 的 Click 事件触发调度并很好地更改存储状态。 但是在测试运行器中,由于渲染是孤立的,似乎会导致错误。 存储状态已更改,但道具已通过仍未更改 所以我改变了 Child 数据结构,不是从 Parent 获取 props,而是从 store 获取。

【讨论】:

    【解决方案2】:

    因为如果你不等待,你就会得到一个承诺,这是一个真实的价值。 现在,如果您确实等待并且仅在这种情况下承诺解析为虚假值,您的测试用例将失败

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      相关资源
      最近更新 更多