React 测试库:如何在 setInterval 更新的文档中查找文本?

React Testing Library: How to find text in the document which is updated by setInterval?

我有一个计数器(React hooks 组件),它每秒递增地呈现一个新数字。 在挂钩更新时,我如何断言某个数字在 DOM 中?

这是一个code sandbox link

import React, { useState, useEffect } from "react";

export default function Counter() {
  const [count, setCount] = useState(1);

  useEffect(() => {
    const intervalId = setInterval(function () {
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(intervalId);
  });

  return <span>{count}</span>;
}

未通过测试

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

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

通过测试

  test("should render one and then two and then three", 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();
  });

根据documentation,默认超时是1000ms,所以我认为它在显示3之前就超时了。

如果把测试修改成下面这样呢?

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

  const three = await waitFor(() => screen.findByText(/3/i), {
    timeout: 3000
  });
  expect(three).toBeInTheDocument();
});