使用 Jest 和 Enzyme(在 Symfony 中)进行 React 测试得到“语法错误:意外的令牌导入”

PiM*_*iML 5 reactjs jestjs babeljs enzyme symfony4

我在 Symfony 中使用 React,安装了 Jest 和 Enzyme 来测试 React 组件,但是在尝试运行测试时yarn test甚至yarn test --no-cache出现以下错误: 在此处输入图片说明

这是我的 package.json 文件:

{
  "devDependencies": {
    "@symfony/webpack-encore": "^0.20.1",
    "babel-jest": "^23.2.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "enzyme-to-json": "^3.3.4",
    "jest": "^23.2.0",
    "jest-enzyme": "^6.0.2",
    "webpack-notifier": "^1.6.0"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "moment": "^2.22.2",
    "prop-types": "^15.6.2",
    "rc-datetime-picker": "^1.6.1",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react-redux": "^5.0.7",
    "redux": "^4.0.0"
  },
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch"
  },
  "jest": {
    "transform": {
      "^.+\\.js$": "babel-jest"
    },
    "setupTestFrameworkScriptFile": "./assets/js/__tests__/setup/setupEnzyme.js",
    "testPathIgnorePatterns": [
      "./assets/js/__tests__/setup/"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

和我的 webpack.config.js(encore) 文件:

var Encore = require('@symfony/webpack-encore');

Encore
// the project directory where all compiled assets will be stored
    .setOutputPath('public/build/')

    // the public path used by the web server to access the previous directory
    .setPublicPath('/build')

    // will create public/build/app.js and public/build/app.css
    .addEntry('app', './assets/js/index.js')

    // allow legacy applications to use $/jQuery as a global variable
    .autoProvidejQuery()

    // enable source maps during development
    .enableSourceMaps(!Encore.isProduction())

    // empty the outputPath dir before each build
    .cleanupOutputBeforeBuild()

    // show OS notifications when builds finish/fail
    .enableBuildNotifications()

    .enableReactPreset()

    // first, install any presets you want to use (e.g. yarn add babel-preset-es2017)
    // then, modify the default Babel configuration
    .configureBabel(function(babelConfig) {
        // add additional plugins
        babelConfig.plugins.push('transform-object-rest-spread');

        // no plugins are added by default, but you can add some
        // babelConfig.plugins.push('styled-jsx/babel');
    })

// create hashed filenames (e.g. app.abc123.css)
// .enableVersioning()

// allow sass/scss files to be processed
// .enableSassLoader()
;

// export the final configuration
module.exports = Encore.getWebpackConfig();
Run Code Online (Sandbox Code Playgroud)

最后是我的 setupEnzyme.js:

const Enzyme = require('enzyme');
// this is where we reference the adapter package we installed
// earlier
const EnzymeAdapter = require('enzyme-adapter-react-16');
// This sets up the adapter to be used by Enzyme
Enzyme.configure({ adapter: new EnzymeAdapter() });
Run Code Online (Sandbox Code Playgroud)

我尝试了所有可用的解决方案,但没有一个对我有用!有什么想法吗?:(

kam*_*cki 0

我知道这个回复是在帖子创建大约两年后出现的,但是我在 React/Symfony 5/Encore 设置下的 Jest/Enzyme 测试中也遇到了类似的问题。这是该问题的有效解决方案:

  1. 从 webpack.config.js (Encore 使用)注释 Babel 配置,并使用常规 babel.config.js 文件创建自定义配置:
  • webpag.config.js - 注释 Encore configureBabelPresetEnvbabel 设置:
/*
 * Commented as babel.config.js is used
 * The "callback" argument of configureBabelPresetEnv()
 * will not be used because your app already provides an
 * external Babel configuration (e.g. a ".babelrc" or "babel.config.js" 
 * file or "babel" key in "package.json").
 */
//enables @babel/preset-env polyfills
//.configureBabelPresetEnv((config) => {
//    config.useBuiltIns = 'usage';
//    config.corejs = 3;
//})

Run Code Online (Sandbox Code Playgroud)
  • babel.config.js - 在项目的根目录创建此配置文件。它将为 Jest 提供 babel 预设并重载 Encore 配置的一部分(之前在 webpack.config.js 中注释过):
module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                    browsers: [
                        "> 0.5%",
                        "last 2 versions",
                        "IE 11"
                    ]
                },
                useBuiltIns: 'usage',
                corejs : {
                    version: "3",
                    proposals : true
                }
            },
        ],
        ['@babel/preset-react'],
        ['@babel/preset-typescript']
    ],
    plugins: ["@babel/plugin-syntax-jsx"]
};
Run Code Online (Sandbox Code Playgroud)
  1. 使用以下文件设置 Jest:
  • setup.js - 在测试目录中创建文件
import React from 'react';

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });
Run Code Online (Sandbox Code Playgroud)
  • 最后使用以下行更新 jest.config.js 文件:
module.exports = {
    rootDir: './assets',
    //test files
    testRegex: './assets/js/.*test\\.js$',
    //setup 
    setupFiles: ['<rootDir>/tests/setup.js'],
    //alias list to integrate swiftly nested directories
    //this can be skipped if not needed
    moduleNameMapper: {
        '^@constants(.*)$': '<rootDir>/js/constants',
        '^@containers(.*)$': '<rootDir>/js/containers',
        '^@store(.*)$': '<rootDir>/js/store',
         //identity-obj-proxy to integrate styles/images etc.
         //this can be skipped if not needed
        '\\.(css|less|scss|jpg|jpeg|png)$': 'identity-obj-proxy'
    }
};
Run Code Online (Sandbox Code Playgroud)

我用来使 Jest/Enzyme 与 React/Symfony 5 配合使用的依赖项列表:

npm install --save-dev jest
npm install --save-dev enzyme
npm install --save-dev enzyme-adapter-react-16 
npm install --save-dev @babel/plugin-syntax-jsx
npm install --save-dev @babel/preset-typescript
npm install --save-dev identity-obj-proxy
Run Code Online (Sandbox Code Playgroud)

最终实现可以在这里找到: symfony-react-jest-enzyme

瞧,希望这会对某人有所帮助。