首页 文章

Jest,意外的令牌导入

提问于
浏览
10

我启动了一个新的反应项目,并且我使用Jest作为测试平台 . 尽管文档,博客和许多其他资源,如stackoverflow,我总是有一个“意外的令牌导入”错误可能与babel问题有关,但我的conf似乎没问题 . 欢迎任何帮助 .

我的Jest conf(在package.json中) . 我的package.json有依赖,如babel-jest,babel-preset-es2015,babel-preset-react等 .

"jest": {
    "testMatch": [
      "**/?(*.)spec.js?(x)"
    ],
    "moduleDirectories": [
      "src",
      "node_modules"
    ],
    "moduleNameMapper": {
      "^lib/(.*)$": "<rootDir>/src/lib/$1",
      "^components/(.*)": "<rootDir>/src/components/$1",
    },
    "transform": {
      "^.+\\.jsx?$": "babel-jest"
    }

我的.babelrc conf:

{
  "presets": [
    ["es2015", { "modules": false }],
    "react"
  ],
  "plugins": [
    ["react-hot-loader/babel"],
    ["transform-object-rest-spread", { "useBuiltIns": true }],
    ["transform-runtime"]
  ],
  "env": {
      "test": {
        "presets": ["es2015", "react"]
      }
  } 
}

我的spec文件:

import React from 'react';
import Radio from 'components/ui/radio';
...

和components / ui / radio(第一行引发导入错误):

import Container from './container.jsx';
...

我的webpack有两个名为lib和components的别名(在jest中定义为moduleNameMapper) .

...
resolve: {
   mainFiles: ['index', 'main'],
   extensions: ['.js', '.jsx'],
   alias: {
     lib: helpers.getPath('src/lib/'),
     components: helpers.getPath('src/components/'),
   },
   modules: [
     helpers.getPath('src'),
     helpers.getPath('node_modules'),
   ],
}, 
...

1 回答

  • 4

    我有一个非常相似的问题,最后我在运行jest时使用--no-cache解决了它 .

    我也有我的package.json依赖项,如babel-jest,babel-preset-es2015,babel-preset-react等 .

    jest --no-cache
    

相关问题