React — Testing Redux Components with Shallow Rendering
When testing React components you want to be very specific about what’s being tested, keeping everything lightweight. Loads of configuration in a test is usually a sign something is not right with your approach to the test (or the component).
You should always be looking to use shallow rendering. This is a real unit test, provides an element of isolation and child elements aren't rendered. Helpful methods like instance can be called giving access to properties on the component allowing you to interact directly.
For most low level components shallow rendering is easy to setup and use. Redux components can be more troublesome. If your component is wrapped in the <Provider> service you can’t take advantage of shallow rendering due to it being applied to that instead.
There is a way around this. A mock Redux store is still required, only this is passed directly to the component as props. Consider the following example.
The important thing to notice is how the component is exported from the component file and imported into the test file. The component class (minus the redux wrapping) is exported in addition to the file’s default which remains wrapped in redux. The component is imported into the test file with curly braces; this pulls in the entity with that specified name (and not the file’s default).
Having to specify each part of the store as an individual prop on the component would be pretty tedious; so I’ve made a utility function. The ShallowMock utility takes a React component and a props object (think redux store). Using React’s cloneElement method, both parameters are combined into a new component and returned.
This new instance is then passed to the shallow call to be rendered allowing you to use the Shallow API to write some tests.
(Note the above example uses Enzyme’s Shallow Rendering API)
