【问题标题】:Code splitting `import` breaks Jest tests代码拆分 `import` 会破坏 Jest 测试
【发布时间】:2017-11-22 10:10:42
【问题描述】:

我正在使用webpack的代码拆分功能,但是jest似乎无法识别import()函数:

        import('myModule').then(function (myModule) {
        ^^^^^^
SyntaxError: Unexpected token import

我没有任何特殊设置。我的 npm 测试脚本只是运行 jest "test": "jest"

我怎样才能让它工作?

我正在使用最新版本的 jest 20.0.4 和 babel-jest 20.0.3

【问题讨论】:

    标签: javascript unit-testing webpack jestjs


    【解决方案1】:

    哦,我刚刚找到了答案。

    只需安装此插件:https://github.com/airbnb/babel-plugin-dynamic-import-node 并将其添加到.babelrc 文件中:

    {
      ...
      "env": {
        "test": {
          "plugins": ["dynamic-import-node"]
        }
      }
    }
    

    【讨论】:

    • 我一直有同样的issue,这解决了我的问题,谢谢!尽管我还必须始终在 --no-cache 模式下运行 jest 才能使其工作:/
    • 注意,如果你通过ts-jest使用Jest和Typescript,那么这个配置需要添加到{ ... "jest": { "globals": { "ts-jest": { "babelConfig": { "env": { "test": { "plugins": ["dynamic-import-node"] } } } } } } }
    • @DmitriyT 嗨 Dmitry,在哪里添加您提到的配置? .babelrc 还是开玩笑的配置?
    猜你喜欢
    • 2015-01-08
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 2021-02-07
    • 2019-08-20
    相关资源
    最近更新 更多