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

Nul*_*ead 2 javascript unit-testing setinterval reactjs react-testing-library

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

这是代码沙箱链接

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>;
}
Run Code Online (Sandbox Code Playgroud)

测试失败

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

    const three = await waitFor(() => screen.findByText(/3/i));
    expect(three).toBeInTheDocument();
  });
Run Code Online (Sandbox Code Playgroud)

通过测试

  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();
  });
Run Code Online (Sandbox Code Playgroud)

小智 6

根据文档,默认超时是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();
});
Run Code Online (Sandbox Code Playgroud)