繁体   English   中英

create-react-app、代码拆分和玩笑

[英]create-react-app, code splitting and jest

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

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
    )
});

我必须如何导出/导入我的组件才能正确测试它们。

谢谢。

如果你在 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 语法。


还要检查“ JavaScript 中的导出默认值是什么?

通过这篇文章找到了一个解决方案: React router dynamic routes not rendering component

使用 es6 模块导出时,我只需要在 require 语句中添加“default”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM