Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React testing library to cover the lazy load

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'

 ...
like image 405
Ankit Kumar Gupta Avatar asked Feb 18 '26 15:02

Ankit Kumar Gupta


1 Answers

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())
})
like image 157
Ankit Kumar Gupta Avatar answered Feb 20 '26 07:02

Ankit Kumar Gupta