【问题标题】:React Testing Library: Why does the order of the tests matter?React 测试库:为什么测试的顺序很重要?
【发布时间】:2020-11-06 16:43:42
【问题描述】:

这是link to codesanbox

重新排序以下测试将使find one after the other 测试通过。

另一种让它通过的方法是让should be able to find 3 directly 测试通过,例如,让它找到2 而不是3

describe("Counter", () => {
  test("should be able to find 3 directly", async () => {
    render(<Counter />);

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });

  test("find one after the other", async () => {
    render(<Counter />);

    const one = await waitFor(() => screen.findByText(/1/i));
    expect(one).toBeInTheDocument();

    const two = await waitFor(() => screen.findByText(/2/i));
    expect(two).toBeInTheDocument();

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });
});

所以问题是,为什么测试的顺序很重要?为什么clean up 不起作用?

【问题讨论】:

  • Counter 正在使用 setInterval 所以第二个测试通过基本上是幸运的。通常任何取决于特定日期/时间的测试,无论是否反应,您都可以使用fake timers 来指定/控制时间增量。对于计数器,您将设置假计时器,然后将时间更新为 3 秒后,以便您可以检查文本 3 是否出现。此外,您可能没有在组件useInterval 中正确使用 setInterval。
  • 我要补充一点,虽然有反应测试库方法可以等待文本出现,但假计时器是在 jest、mocha、tape 或任何其他库中如何控制时钟以确保事情正在按照您期望的方式出现/执行。

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


【解决方案1】:

看起来waitFor 在等待计数器为 3 时已达到超时,这意味着我猜在这种情况下它与订购无关。

您可以通过增加等待计数器的超时时间来解决如下问题:

test("should be able to find 3 directly", async () => {
  render(<Counter />);

  const three = await waitFor(() => screen.findByText(/3/i), {
    timeout: 3e3, // 3s wait would find 3
  });

  expect(three).toBeInTheDocument();
});

【讨论】:

  • 我明白了,我错误地假设超时时间为 5 秒。 testing-library.com/docs/dom-testing-library/api-async#waitfor
  • 那么为什么"same as the first test but fails because the second test is failing" 测试只有在"should be able to find 3 directly" 测试失败时才会失败?
  • 是的,看起来很有趣。我猜它会抛出错误,因为waitFor 在所有执行的测试用例中达到其限制超时(因为它们是异步运行的)
猜你喜欢
  • 2011-12-13
  • 2022-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多