Testing react-lazyload in React testing library

Viewed 369

I am unit testing a component that makes use of react-lazyload to lazyload stuff. While rendering in my unit test, I noticed that the Lazyload is not rendering the content and its placeholder is being shown. I tried using waitFor with async/await to wait for lazily loaded content to render in next tick cycle but it still fails and screen.debug() still shows the placeholder in the dom.

Is there any way I can test such a component? Here is what I tried:

render(<WrapperComponent />)
await waitFor(() => { 
  expect(screen.getByText('Lazily loaded text!')).toBeInTheDocument()
});

// source code
import LazyLoad from 'react-lazyload';
const WrapperComponent = () => {
  return (
    <div>
      <LazyLoad placeholder="Loading..." >
        <div>Lazily loaded text!</div>
      </LazyLoad>
    </div>
  );
}

Lazily loaded content has a div with the text being expected above.

1 Answers

Test does not actually trigger real data fetch, you have to mock it. Probably the function that requests for data should be the one you mock.

Related