create-react-app, code splitting 和 jest

create-react-app, code splitting and jest

我正在使用 create-react-app 开发一个应用程序,我正在尝试将我的代码拆分为实现 react-router huge-apps 示例中描述的方式的模块。 除了单元测试之外,一切都很好:我在 运行 对路由组件进行开玩笑测试时收到此错误:

TypeError: Cannot read property 'contextTypes' of undefined

路由组件如下所示:

export class IntroPage extends React.Component {
    render() {
        return (
            <div></div>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        ...
    }
};

module.exports = connect(mapStateToProps)(IntroPage);

还有一个测试:

import React from 'react';
import {shallow} from 'enzyme';
import {IntroPage} from '../IntroPage';

it('should render without crashing', () => {
    shallow(
        <IntroPage {...props}/> // IntroPage is undefined
    )
});

我如何 export/import 我的组件才能正确测试它们。

谢谢。

找到解决方案 post :

我只需要在使用 es6 模块导出时将 'default' 添加到 require 语句中。

如果你在 Babel 中转译:

export class IntroPage extends React.Component {
   ...
}

您会注意到 Babel 会将其移动到 exports 变量。

Object.defineProperty(exports, "__esModule", {
    value: true
});
... more good stuff
...
var IntroPage = exports.IntroPage = function (_React$Component) {

所以你可以console.log这些:

console.log(exports);
console.log(module.exports);
console.log(module);

并检查 exports 变量和 module 对象。 这里 module.exports 应该与 exports.

相同

如果您键入:

 module.exports = connect(mapStateToProps)(IntroPage);

在组件文件的末尾,您正在用新值覆盖 module.exports

这就是问题的核心。

解决方案?

我想你已经找到了,但最好不要将 commonJS 与 ES6 导出混合使用,因为 ES6 导出将被转换为 commonJS 语法。


同时检查“What is export default in JavaScript?