Enzyme: Test asynchronous dynamic imported components

Created on 10 Jul 2017  路  2Comments  路  Source: enzymejs/enzyme

How can I test components that look like following:

class MyComponent extends React.Component {
  constructor() {
    this.state = {
      imported: false;
    }
  }

  render() {
    if (someCondition && !this.state.imported) {
      this.loadComponent();
    }
    return (
      <div>
        <p>Hello world</p>
        {this.otherComponent}
      </div>
    )
  }

  async loadComponent() {
    this.otherComponent = await import('./OtherComponent');
    this.setState({ imported: true });
  }
}

I am aware of the issue #346 (Testing Async Components) but this doesn't help much because I don't use any library that I could mock. I use import() explicitly here because I want to load a really heavy React component only under some circumstances.

question

All 2 comments

You'd want to make sure you're using a babel transform in tests that makes import() work in node.

Then:

const wrapper = shallow(<MyComponent />);
return wrapper.instance().loadComponent().then(() => {
  wrapper.update();
  // assertions
});

Thank you. It does work in my case. It's not sooo beautiful because the test knows about the internal privat implementation (.loadComponent()) and in TypeScript I have to make it public (it was private in my project) but it seems that this is the best solution.

馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ahuth picture ahuth  路  3Comments

dschinkel picture dschinkel  路  3Comments

AdamYahid picture AdamYahid  路  3Comments

timhonders picture timhonders  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments