Assuming you would want to unit-test container components in React (i.e., connected components in a Redux-based project), or any component that is wrapped in a higher-order component (HOC) etc. really, here’s a simple thing you should always do:

πŸ‘‰ Also export the “naked” component!

I am talking about something like this:

// ...

export { MyComponentContainer };

export default connect( ... )( MyComponentContainer );

If you were to use the actual container, then it’s not unit testing any longer anyway, because you would not (only) test the component, but also the wrapper. Also, depending on what tools/libraries you are using, you are not even able to actually unit-test this. For example, Enzyme’s shallow rendering will just stop after resolving the connect call, and you are unable to access state, props, object properties or methods of the component that you want to test.

In your test file(s), you would then import both the “naked” named export and the wrapped component:

import MyComponentContainer, { MyComponentContainer as Naked } from '../path/to/MyComponentContainer';

Instead of Naked, call it whatever you want. You could also have MyComponentContainer as the component itself, and then import the default (i.e., the connected component) as Wrapped or something along these lines…

This goes in addition to using something like the redux-mock-store, which you still do whenever you want to test functionality related to redux. But not every single thing the component does requires this, so why not properly unit-test these things, right?

If you don’t care about proper unit tests, then you can ignore this. (But maybe you still just do that.)

Leave a Reply

Your email address will not be published. Required fields are marked *