Vishal
Vishal

Reputation: 10964

Testing react-lazyload in React testing library

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.

Upvotes: 1

Views: 1973

Answers (3)

GalAbra
GalAbra

Reputation: 5138

You can utilize forceVisible:

import { forceVisible } from 'react-lazyload';

it('Testing a component using react-lazyload', async () => {
  const screen = render(<WrapperComponent />)
  forceVisible();

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

Upvotes: 0

Shaleen Kachhara
Shaleen Kachhara

Reputation: 46

We can mock the LazyLoad component from react-lazyload library at the top of our test file so that the LazyLoad component behave just like a wrapper around our actual component that we need to test for.

jest.mock(
  'react-lazyload',
  () =>
    function LazyLoad({ children }) {
      return <>{children}</>
    }
)

test('component wrapped with Lazyload', () => {
  const {screen} = render(< WrapperComponent />)
  expect(screen.getByText('Lazily loaded text!')).toBeInTheDocument()
})

Upvotes: 1

Nectos
Nectos

Reputation: 206

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.

Upvotes: 0

Related Questions