【问题标题】:Jest test case gives Unexpected token in dynamic import() errorJest 测试用例在动态 import() 错误中给出了 Unexpected token
【发布时间】:2018-07-10 07:28:08
【问题描述】:

我使用create-react-appreact-scripts-ts 生成了一个react 应用程序,并弹出以配置webpack。我正在使用react-async-component 异步渲染页面。

import { asyncComponent } from 'react-async-component';

const AsyncNotFoundPage = asyncComponent({
    resolve: () => import('./NotFoundPage').then(x => x.default)
});

export { AsyncNotFoundPage };

当我启动应用程序时,它会按预期工作。它拆分未找到页面的块。但是,以下开玩笑的测试用例给出了错误;

describe('AsyncNotFoundPage Component', () => {

    it('should render async', () => {
        const wrapper = shallow(<AsyncNotFoundPage />);
        expect(wrapper.find(NotFoundPage)).toBeTruthy();
    });
});

它给出了以下错误;

Unexpected token import

我尝试将所有动态导入插件添加到 package.json 中的 babel 配置中。它不起作用。

有什么想法吗?

【问题讨论】:

  • 你尝试过 require('moduleName').我遇到了同样的错误,它通过使用 require('') 解决了
  • 你能分享 babel 配置吗.. 我正在添加一个通用解决方案。希望它有效
  • @hannadrehman babel config 默认只有react-app 预设
  • 你可以试试下面的答案。我确定是因为测试环境没有动态导入插件

标签: reactjs typescript babeljs jestjs create-react-app


【解决方案1】:

安装 babel-jest

npm install --save-dev babel-jest

为环境配置 .babelrc Jest 会将您的NODE_ENV 更改为“test”,而 Babel 没有针对此环境的任何配置,我们通常为开发和生产环境定义 Babel 配置。当没有 babel 转译时,import 关键字实际上变得未定义,因为它实际上不存在于 JS 上下文中。

更新您的.babelrc 以匹配关注

{
  "presets": [
    "env",
    "react"
  ],
  "plugins": [
    "transform-class-properties",
    "transform-object-rest-spread"
  ],
  "env": {
    "test": {
      "presets": [
        "env",
        "react"
        ],
      "plugins": [
        "transform-class-properties",
        "transform-object-rest-spread",
        "dynamic-import-webpack"
      ]
    }
  }
}

如果您正在使用其他一些插件,请将它们也添加到测试环境中

将 jest.congfig.json 添加到项目根目录

{
  "transform": {
    "^.+\\.jsx?$": "babel-jest"
  }
}

使用 jest 配置更新您的 package.Json

"jest": {
"transform": {
        "^.+\\.jsx?$": "babel-jest"
      }
}

如果您使用的是jest.config.json

"scripts": {
    "test": "jest --config=jest.config.json --watch"
},

否则

"scripts": {
        "test": "jest --watch"
    },

【讨论】:

  • 这会在打字稿中运行吗?
  • react-scripts-ts 使用 babel。你需要找到保存 babelrc 文件的位置
  • 弹出后,babel config 驻留在 package.json 中
  • 当我在 tsconfig.test.jcon 中将 compilerOptions.module 覆盖为 commonjs 并在 tsconfig.json 中禁用 allowSyntheticImports 时,它可以工作
猜你喜欢
  • 2018-08-22
  • 2019-02-06
  • 2017-05-02
  • 2017-09-16
  • 1970-01-01
  • 2020-01-15
  • 2018-09-11
  • 1970-01-01
  • 2016-10-04
相关资源
最近更新 更多