Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How test a React Loadable component

I have this component:

import React from 'react';

const UploadAsync = Loadable({
  loader: () => import('components/Upload'),
  loading: () => <LoadingComponent full />
});

const Component = () => {
  return <UploadAsync />
}

export default Component

And the test:

import React from 'react';
import Component from './index';

describe('Component', () => {
  it('should render correctly with upload component', () => {
    const tree = create(<Component />).toJSON();

    expect(tree).toMatchSnapshot();
  });
});

How I can see the Upload component and not the Loading component in the snapshot?

exports[`Content should render correctly with form component 1`] = `
  <div>
    <Loading
      full={true}
    />
  </div>
`;

So far I have tried setTimeOut and Promises.

like image 719
Albert Olivé Avatar asked May 04 '18 13:05

Albert Olivé


2 Answers

Use Loadable.preloadAll() before the tests then you can access the Component you need.

Docs

Simple example:

all imports here

Loadable.preloadAll()

describe('TestName', () => {
 //tests
})

like image 86
Anton Dmitrievich Avatar answered Oct 13 '22 01:10

Anton Dmitrievich


I haven't been able to figure this out either, but here are a couple of workarounds that, alone or together, may work reasonably well:

Snapshot test the components that are passed to Loadable

In your case, the test would look something like this:

import React from 'react';
import Component from './components/Upload';

describe('Component', () => {
  it('should render correctly with upload component', () => {
    const tree = create(<Component />).toJSON();

    expect(tree).toMatchSnapshot();
  });
});

You could also test <LoadingComponent full /> in a similar fashion. No, this doesn't assure you that the Loadable component is working, but you may find it satisfactory to assume that the react-loadable library is well tested and will work as long as you pass to it your own, properly tested components.

End-to-end browser testing

Using a framework such as Selenium or TestCafe you can write tests that run against your site as it runs in a real browser.

like image 22
fagerbua Avatar answered Oct 13 '22 01:10

fagerbua