React testing library to cover the lazy load
Asked Answered
G

2

13

How to cover the lazy load component in react testing library.

import React, {lazy} from 'react';
const ownerInfo = lazy(() => import('../abc'))

const compone = () => {
  return <Suspense><abc /></Suspense>
}
export default compone

test.spec.js

 import React from 'react'
 import {render, fireEvent} from '@testing-library/react'
 import configureStore from 'redux-mock-store'

 ...
Grotto answered 17/3, 2021 at 6:10 Comment(2)
youtube.com/watch?v=lfb5jvHq9c4 This one has proper explanation how to test lazy load one componentsCuvette
Thanks @ShubhamVermaGrotto
G
18

After watching the video, I am able to figure out how to cover the lazy load. Let assume that you have lazyload component.

LazyLoad.jsx:

import React, {lazy} from 'react'
const LazyComponent = lazy(() => import('./LazyComponent'))
const LazyLoad = () => {
   return (
      <div>
         <div> Lazy component is here: </div>
         <React.Suspense fallback={null}>
             <LazyComponent />
         </React.Suspense>
      </div>
   )
}
export default LazyLoad

LazyComponent.jsx:

import React from 'react'
export default () => <div>I am lazy ! </div>

LazyLoad.spec.jsx:

import React from 'react'
import {render, waitFor } from 'react-testing-library'
import LazyLoad from 'LazyLoad'

test('renders lazy component', async () => {
    const { getByText } = render(<LazyLoad />)
    await waitFor(() => expect(getByText('I am lazy !' )).toBeInTheDocument())
})
Grotto answered 18/3, 2021 at 11:46 Comment(1)
Using 'findBy' query could be an option too?Steamy
A
10

According to Kent Dodds, the React Testing Library creator, you should prefer using findByText rather than waitFor + expect.

Those two bits of code are basically equivalent (find* queries use waitFor under the hood), but the second is simpler and the error message you get will be better.

With that in mind, I suggest to refactor your test like this

import React from 'react';
import { render, screen, waitFor } from 'react-testing-library';
import LazyLoad from 'LazyLoad';

test('renders lazy component', async () => {
  const { getByText } = render(<LazyLoad />);
  expect(await screen.findByText('I am lazy !')).toBeInTheDocument();
});
Adjoining answered 30/12, 2022 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.