Unit Testing dynamically imported React Component
Asked Answered
F

0

7

I have a very simple React component that uses react-loadable to dynamically import another component. The code looks something akin to the following:

import React from 'react';
import Loadable from 'react-loadable';
import LoaderComponent from 'path/to/LoaderComponent';


export default outerLoadableComponent = Loadable({
  loader: () => import('path/to/innerComponent'),
  loading() {
    return <LoaderComponent />
  }
});

I am attempting to test this component by using Enzyme to mount outerLoadableComponent, which creates a wrapper around outerLoadableComponent where I can see that the LoaderComponent wrapping it has the loadingState set to true. However, I am stuck at the point where the inner import does not resolve. It seems to be a promise that would only resolve should the import actually go through, however even with some timeouts, it does not work:

const expect = chai.expect;
chai.use(sinonChai);

it('should render the loading state, and innerComponent', (done) => {
  const wrapper = mount(
    <outerLoadableComponent />
  );

  expect(wrapper.loading).to.be.true;

  setTimeout(() => {
    expect(wrapper.loading).to.be.false;
    expect(wrapper.loaded).to.exist; // loaded state returns a function
    expect(wrapper.find(innerComponent)).to.exist;
    done();
  }, 500);
});

My babel-rc has dynamic-import-node so running this outside of the test works all fine. But there seems to be no clear/documented way of mocking (with sinon) the results of an import promise. Any ideas?

Famish answered 3/4, 2018 at 20:44 Comment(1)
Sinon deals with stubbing objects, not interfacing with module loaders. We do document how to do it, though: sinonjs.org/how-to/link-seams-commonjsRiptide

© 2022 - 2024 — McMap. All rights reserved.