Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
381 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...