Jest测试用例在动态import()错误中给出了意外的令牌

时间:2018-01-31 08:44:11

标签: reactjs typescript babel jest create-react-app

我使用create-react-app使用react-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 };

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

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

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

它出现以下错误;

Unexpected token import

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

安装babel-jest

npm install --save-dev babel-jest

为env配置.babelrc Jest会将您的NODE_ENV更改为&#34;测试&#34;而且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"
  }
}

OR 使用jest config

更新您的package.Json
"jest": {
"transform": {
        "^.+\\.jsx?$": "babel-jest"
      }
}

如果您使用jest.config.json

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

其他

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