DrMister DrMister - 2 months ago 10
React JSX Question

Test whether all reducers have been imported in the rootReducer

I have a rootReducer that imports all separate reducers like so:

import { combineReducers } from 'redux';
import departments from './departments';
import indicators from './indicators';
import versions from './versions';
import projects from './projects';

// combine all reducers to a single reducer, state will be linked to a reducer via the key used here
const rootReducer = combineReducers({
versions,
departments,
indicators,
projects,
});

export default rootReducer;


Since it's important for this reducer to import everything, I think it makes sense to test whether all defined reducers in
./src/reducers
are imported. The only method I can think of would use
fs
to check the number of files in
./src/reducers
(without
index
, or the
rootReducer
) and check whether the
rootReducer
contains that many reducers.

Seems like an ugly test, and a bit fragile as well. But still it would be very nice to be notified with a failing test when you forget to include a reducer. What would be the best way to test whether all reducers have been imported?

Answer

I hear where you're coming from but I don't think you want to be dealing with this issue in your tests. As your application grows you're likely want a deeper reducer tree. E.g. your projects reducer may come to be made up of multiple sub-reducers and you'll have to manage which reducers need to be imported from where. The file system test will become more and more brittle. In general, imports and file structures are implementation details of your project and you want to be testing the behavior of your project.

But wanting immediate feedback on failing to hook up a reducer totally makes sense. I'd try to handle it at the build level. Assuming you're using Webpack maybe see if this plugin can solve your problem. It detects unused exports. Add it to your plugins

new UnusedFilesWebpackPlugin({ pattern: 'src/reducers/**' })

and your build will warn you when you have a file that isn't being imported. Since it works with modules you won't have to worry about the directory structure (beyond ensuring that the pattern matches all the files you want to check).

Comments