gpt4 book ai didi

javascript - React 测试库 : How to find text in the document which is updated by setInterval?

转载 作者:行者123 更新时间:2023-12-02 16:25:01 26 4
gpt4 key购买 nike

我有一个计数器(React hooks 组件),它每秒递增地呈现一个新数字。在 Hook 更新时,我如何断言 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();
});

关于javascript - React 测试库 : How to find text in the document which is updated by setInterval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64718253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com