Testing react-loadable components
Asked Answered
T

2

7

I'm having trouble testing my React components that use react-loadable. Say, I have a Button component that, depending on whether it receives an icon prop, loads an Icon component like so:

Button.js

const LoadableIcon =  Loadable({
  loader: () => import('./Icon'),
  loading: () => <div>Loading...</div>
})

function Button(props) {
  return (
    <button 
      onClick={props.onClick}>
      {props.icon &&
        <LoadableIcon name={props.icon} />}
      {props.children}
    </button>
  )
}

When I test this component, however, the Icon had not loaded yet, and instead the test only finds the <div>Loading...</div> element...

Button.test.js

import React from 'react'
import {render} from 'react-testing-library'

import Button from '../Button'


describe('Button', () => {
  it('renders icon correctly', () => {
    const {getByText} = render(
      <Button 
        icon='add' 
      />
    )
    expect(getByText('add')).toBeInTheDocument()
  })
}) 

Is there an elegant way to handle this situation without using actual setTimeouts?

Tommy answered 14/8, 2018 at 9:16 Comment(0)
T
2

So, the answer is to read the docs - note to self! The solution based on docs was the following:

describe('Button', () => {
  it('renders icon correctly', async () => {
    const {getByText} = render(
      <Button 
        icon='add' 
      />
    )
    const icon = await waitForElement(() => getByText('add'))
    expect(icon).toBeInTheDocument()
  })
})

Also, note that async needs to be used together with await.

Tommy answered 24/8, 2018 at 14:17 Comment(0)
B
1

I don't have personal experience using react-loadable, but I have implemented a similar component that handles code splitting via the dynamic import() syntax.

To get Jest to work with 'loadable' / 'async' components, I had to configure my .babel-rc config for Jest to include the dynamic-import-node babel plugin that way the modules can be properly resolved even when the import is async.

Bohon answered 20/8, 2018 at 19:25 Comment(1)
Thanks for the pointer. I'm using create-react-app which doesn't expose .babelrc configuration, which is required to run the linked library, right?Tommy

© 2022 - 2024 — McMap. All rights reserved.