admin管理员组文章数量:1402226
I got a counter (React hooks ponent) which renders a new number incrementally per second. How can I assert a certain number to be in the DOM while it's updated by the hook?
Here's a 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>;
}
Failing test
test("should be able to find 3 directly", async () => {
render(<Counter />);
const three = await waitFor(() => screen.findByText(/3/i));
expect(three).toBeInTheDocument();
});
Passing test
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();
});
I got a counter (React hooks ponent) which renders a new number incrementally per second. How can I assert a certain number to be in the DOM while it's updated by the hook?
Here's a 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>;
}
Failing test
test("should be able to find 3 directly", async () => {
render(<Counter />);
const three = await waitFor(() => screen.findByText(/3/i));
expect(three).toBeInTheDocument();
});
Passing test
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();
});
Share
Improve this question
asked Nov 6, 2020 at 16:26
Null HeadNull Head
2,94113 gold badges64 silver badges87 bronze badges
1 Answer
Reset to default 6According to the documentation, the default timeout is 1000ms, so I think it's timed out before 3 is displayed.
What if you modify the test as follows?
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 Testing Library: How to find text in the document which is updated by setInterval? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744302866a2599665.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论