Reputation: 185
I'm developing an application using create-react-app and I'm trying to split my code into modules implementing the way described in the react-router huge-apps example. Everything works well except the unit tests : I get this error while running the jest tests for the route components :
TypeError: Cannot read property 'contextTypes' of undefined
A route component looks like this :
export class IntroPage extends React.Component {
render() {
return (
<div></div>
);
}
}
const mapStateToProps = (state) => {
return {
...
}
};
module.exports = connect(mapStateToProps)(IntroPage);
and a test :
import React from 'react';
import {shallow} from 'enzyme';
import {IntroPage} from '../IntroPage';
it('should render without crashing', () => {
shallow(
<IntroPage {...props}/> // IntroPage is undefined
)
});
How do I have to export/import my components to be able to test them properly.
Thanks.
Upvotes: 2
Views: 1009
Reputation: 46291
If you transpile in Babel:
export class IntroPage extends React.Component {
...
}
You will notice that Babel will move that to the exports
variable.
Object.defineProperty(exports, "__esModule", {
value: true
});
... more good stuff
...
var IntroPage = exports.IntroPage = function (_React$Component) {
So you can console.log these:
console.log(exports);
console.log(module.exports);
console.log(module);
and check exports
variable and module
object.
In here module.exports
should be the same as exports
.
If you type:
module.exports = connect(mapStateToProps)(IntroPage);
at the end of your component file, you are overwriting the module.exports
with the new value.
This is the core of the problem.
I think you already found one, but the best would be not to mix commonJS with ES6 export, since ES6 export will be transpiled to commonJS syntax.
Check also "What is export default in JavaScript?"
Upvotes: 1
Reputation: 185
Found a solution with this post : React router dynamic routes not rendering component
I just had to add 'default' to the require statements when exporting with es6 module.
Upvotes: 0