unable to test timeout function within useEffect hook

Viewed 174

I am creating a lazyload image loader component that will load image if it is visible for more than 500ms.

It is working as expected but I am unable to write a test to validate it

I have tried jest.runallTimers, setTimeout but no success. I have googled about how to test code with settimeout in useEffect hook but none have worked for me.

I am sharing a codesandbox link in case anybody interested to help.

https://codesandbox.io/s/optimistic-aryabhata-1dtru?file=/__tests__/index.test.js

2 Answers

Try it with jest's done():

it('your async test case', (done) => {

    setTimeout(() => {
        // your expect statement
        done();
    }, 1000);

});

For testing the image that renders after some time you can do this:

it("shows Loading and then renders the image", async (done) => {
  render(<LazyloadImage />);

  expect(await screen.findByTestId("fallbackText")).toBeInTheDocument();

  expect(
    await screen.findByTestId("image", {}, { timeout: 500 })
  ).toBeInTheDocument();

  done();
});

There's something wrong with your custom hook(causing tests to fail), so I removed it from the component but left everything else to render the image after 500ms.

Here's a working sandbox

Related