【问题标题】:React Jest - Unexpected token importReact Jest - 意外的令牌导入
【发布时间】:2018-01-21 07:52:06
【问题描述】:

我正在学习反应,我想test one of my components,但我遇到了这个错误:

{import React from 'react';                                                                                   
^^^^^^
SyntaxError: Unexpected token import

这是我在阅读 stackoverflow 和 github 上的帖子时尝试过的一些事情

在我的 babel 配置中添加了测试预设和这些插件 "transform-es2015-modules-commonjs", dynamic-import-node"

{
  "presets":  ["es2015", "react"],
  "env": {
  "test": {
      "presets":[
        ["es2015", { "modules": false }],
         "stage-0",
        "react"],
      "plugins": [
        "transform-es2015-modules-commonjs",
        "dynamic-import-node"
      ]
    }
}
}

在我的 package.json 中,Jest 属性具有以下设置:

"jest": {
    "verbose": true,
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "jsx",
      "js"
    ],
   "transform": {},
    "moduleDirectories": [
      "node_modules"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!react)/"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
  },

我的actual component 是用 ES6 和 typescript 构建的,如果对你有帮助的话:)

从我读到的内容来看,导入时似乎很有趣,因为节点不理解 ES6 导入。我在网上尝试过的所有解决方案似乎都不起作用。

这里还有我的开发依赖:

"devDependencies": {
    "awesome-typescript-loader": "^3.2.2",
    "babel-cli": "^6.24.1",
    "babel-core": "^6.25.0",
    "babel-eslint": "^7.2.3",
    "babel-jest": "^20.0.3",
    "babel-loader": "^7.1.1",
    "babel-plugin-dynamic-import-node": "^1.0.2",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "css-loader": "^0.28.4",
    "enzyme": "^2.9.1",
    "eslint": "^4.4.1",
    "eslint-config-airbnb": "^15.1.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-import": "^2.7.0",
    "eslint-plugin-jsx-a11y": "^6.0.2",
    "eslint-plugin-react": "^7.2.0",
    "extract-text-webpack-plugin": "^3.0.0",
    "html-webpack-harddisk-plugin": "^0.1.0",
    "html-webpack-plugin": "^2.30.1",
    "jest": "^20.0.4",
    "node-sass": "^4.5.3",
    "react-test-renderer": "^15.6.1",
    "regenerator-runtime": "^0.10.5",
    "sass-loader": "^6.0.6",
    "source-map-loader": "^0.2.1",
    "style-loader": "^0.18.2",
    "ts-jest": "^20.0.10",
    "typescript": "^2.4.2",
    "webpack": "^3.5.1",
    "webpack-dev-middleware": "^1.12.0",
    "webpack-dev-server": "^2.7.0"
  },

Webpack 配置

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');

const HOST = "127.0.0.1";
const PORT = "9000";

const devServerUrl = "http://localhost:" + PORT + "/";

const config = {
  devtool: 'source-map',
  context: __dirname, // `__dirname` is root of project and `src` is source
  entry:
  [
    './src/index.js',
    './src/ui/styles.scss'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: "bundle.js",
    publicPath: ''
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.scss', '.css']
  },
  module: {
    rules: [
      { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
      { test: /\.js$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
      { test: /\.jsx$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
      {
        test: /\.(sass|scss)$/, use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader']
        })
      }
    ]
  },
  devServer: {
    contentBase: "dist/",
    noInfo: true,
    inline: true,
    compress: true,
    port: PORT,
    host: HOST,
    hot: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html', // Output file name.
      template: './public/index.html', // Use our HTML file as a template for the new one.
      inject: 'body',
      alwaysWriteToDisk: true,
      output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js'
      },
    }),
    new ExtractTextPlugin({ // define where to save the file
      filename: 'styles.bundle.css'}),
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackHarddiskPlugin({
  outputPath: path.resolve(__dirname, 'dist')
})
  ],
};

module.exports = config;

谢谢

【问题讨论】:

    标签: reactjs unit-testing ecmascript-6 jestjs babel-jest


    【解决方案1】:

    你需要安装 babel 来编译你的 es6 和 react 代码

    使用

       C:\Users\username\Desktop\reactApp>npm install babel-core
    C:\Users\username\Desktop\reactApp>npm install babel-loader
    C:\Users\username\Desktop\reactApp>npm install babel-preset-react
    C:\Users\username\Desktop\reactApp>npm install babel-preset-es2015
    

    尽量保持我们的 webpack 为

    var config = {
       entry: './todoApp.js',
    
       output: {
          path:'./',
          filename: 'index.js',
       },
    
       devServer: {
          inline: true,
          port: 9191
       },
    
       module: {
             rules: [
          {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
          }
          ],
          loaders: [
             {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel',
    
                query: {
                   presets: ['es2015', 'react']
                }
             }
    
          ]
       }
    }
    
    module.exports = config;
    

    【讨论】:

    • 我已经有了,你可以在依赖列表中看到它们
    • 我添加了我的 webpack 配置,所以你可以看到我也在使用 babel loader
    • 尝试根据我的代码而不是规则将您的测试内容定义到加载器中
    【解决方案2】:

    这是因为你已经将 babel 配置为转译 ES6 模块

      "presets":[
        ["es2015", { "modules": false }],
    

    再试一次modulestrue(或省略,因为它默认为true),它应该可以工作。

    【讨论】:

    • 我将其设置为 true 以查看是否有帮助,但没有。我的测试确实有这样的配置:“env”:{“test”:{“presets”:[“es2015”,“stage-0”,“react”],“plugins”:[“transform- es2015-modules-commonjs", "动态导入节点" ] } }
    • 嗯,肯定就是这样。将您的配置与我的配置进行比较,我并没有真正看到任何其他差异。尝试删除那些模块/导入插件 - 我只需 "presets": [ "es2015", "stage-0", "react" ] 就可以正常工作
    • 你是怎么玩笑话的?我在我的 package.json 中设置了它,以便在我输入 npm test 时运行 jest。所以我不使用 webpack 来运行测试。那是我在哪里,出错了吗?顺便说一句,同样的问题 - "presets": [ "es2015", "stage-0", "react" ]
    • 我也是这样做的,只是从npm test 运行jest - 作为最后一击,您确定 jest 采用了"env": "test": ... 配置吗?还是只是使用普通的?为了消除这种情况,我会尝试改变两者,看看会发生什么。或者只是使用一个 .babelrc 文件来开玩笑
    • 我不认为它正在查看 babel 文件中的任何内容,因为我将 stage-0 更改为 stage-1,这是我没有的预设并且它没有错误
    【解决方案3】:

    Jest 不适用于 Typescript。

    我已经从我的项目中删除了 Jest,并安装了 Mocha、Karma、Chai 和 Enzyme。

    与伪装成以下角色的 Jest 相比,设置起来毫不费力:

    零配置测试平台

    这篇文章帮了大忙:Getting Started on Testing with Typescript, ReactJS, and Webpack

    希望这将避免其他人浪费时间让 Jest 使用 Typescript。

    【讨论】:

    猜你喜欢
    • 2017-03-24
    • 2018-01-20
    • 2018-01-17
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2019-06-29
    相关资源
    最近更新 更多