1

When I test my code using useEffect with setTimeout I got an error, how to solved the error?

TestingLibraryElementError: Unable to find an element with the text: My Title. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible

This my code.

PostPage.js

function PostPage() {
  const [title, setTitle] = useState(null);
  useEffect(() => {

      const timmer = setTimeout(() => {
          setTitle("My Title");
      }, 3000);

      return () => {
          clearTimeout(timmer);
      };
   }, []);


   return (
      <Container>
         <div className="posts-container">
            <Header title={title} />
         </div>
       </Container>
    );
  }
  
  export default PostPage;

PostPage.test.js

describe("Render Post Page", () => {
   it('Render Page Title "My Title"', () => {
       const { debug, container } = render(<PostPage />);
       const title = screen.getByText("My Title");
       expect(title).toBeInTheDocument();
   });
 });

Any solution?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Encang Cutbray
  • 382
  • 1
  • 2
  • 9
  • 2
    Does this answer your question: [How to check what react component displays after delay in a test](https://stackoverflow.com/questions/64401853/how-to-check-what-react-component-displays-after-delay-in-a-test)? Use `jest.useFakeTimers`/`jest.advanceTimersByTime` in your test. – juliomalves Oct 24 '21 at 17:04

0 Answers0