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.
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.
馃憤