Search code examples
reactjswebpackreduxreact-reduxkarma-webpack

Redux + karma-webpack - cannot read displayName of undefined upon import of React.Component


I'm using karma-webpack and I am refactoring a React Component to use in multiple places. I moved the component to it's own file, so I can import it and connect it differently by applying mapStateToProps / mapDispatchToProps in the HOC I later include on my page.

Here's the scenario:

EventTable - imports EventTableComponent, exports connected / wrapped component MyEventTable - imports EventTableComponent, exports connected / wrapped component EventTableComponent - defines the props / behaviors shared to render the data rows

When I git mv EventTable to EventTableComponent and refactored the code so the connected stuff is in the HOCs, the tests start failing to import EventTableComponent only in karma-webpack. Chrome works just fine and the view render perfectly. QA is happy, or would be, but my build fails.

The build is failing because WrappedComponent is undefined for the EventTable and MyEventTable components, which causes connect to throw the message in the synopsis (cannot read displayName of undefined), but I don't even import either of these files into my test! Instead, it fails while karma webpack is building, but before running any tests.

I fixed the build locally by destroying the view and making a "fake" / "replacement" like this:

function EventTableComponent () { 
    return (<div>garbage here</div>);
}

The build passes.

The most confusing part in all of this? I don't even test the HOC at all. I import just the EventTableComponent into the test, but karma-webpack, as suggested in the Redux Documentation.

I've written a minimal example gist to illustrate: https://gist.github.com/zedd45/cbc981e385dc33d6920d7fcb55e7a3e0


Solution

  • I was able to solve this by tricking the module system.

    // EventTableComponentWrapper.jsx
    
    import EventTableComponent from './EventTableComponent';
    
    if (process.env.NODE_ENV === 'test') {
        module.exports = require('./EventTableComponent.test.jsx');
    } else {
        module.exports = EventTableComponent;
    }
    

    I import this file in both HOC Components, and based on my environment variable, I get the right one, and Karma Webpack is tricked into not exploding.

    I arrived at this conclusion based on a few leads, but credit goes to this SO Post: Conditional build based on environment using Webpack

    and also to Wout Mertens from the Webpack Gitter channel for tipping me off to the issue being ES6 Class Import / Export related.