reactjs - React Jest - 意外的 token 导入

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

我正在学习 React,我想要 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 构建的,如果这对你有帮助的话:)

从我读到的内容来看,导入时 Jest 似乎令人窒息,因为节点不理解 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;

谢谢

最佳答案

Jest 不适用于 Typescript。

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

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

Zero configuration testing platform

这篇文章提供了巨大的帮助:Getting Started on Testing with Typescript, ReactJS, and Webpack .

希望这能让其他人避免浪费时间让 Jest 与 Typescript 一起工作。

关于reactjs - React Jest - 意外的 token 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45658180/

相关文章:

javascript - 不支持 react 分析

unit-testing - 如何使用 token 对帖子(web-api)调用进行单元测试?

c# - 单元测试 - 断言 Controller 操作返回的对象

javascript - 使用 console.log 作为 promise 回调

javascript - 更改对象属性以匹配给定数组中的值

javascript - 如何将参数传递给 map 函数中的事件处理程序

javascript - ReactJS - 如何为每个字符创建一个具有多种颜色的字符串

reactjs - 使用 'babel' 加载程序时,Node.js 的 Firebase 库会中断。具体是: "Uncaught TypeError: Cannot read property ' navigator' of undefined"

javascript - JS函数显示错误但没有返回,但不需要返回

java - Spring @ContextConfiguration