开玩笑:测试套件无法运行,SyntaxError:意外的令牌导入

发布于 2021-01-31 23:01:16

这是我来自package.json文件的笑话配置

"jest": {
    "automock": false,
    "browser": true,
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "./app/tests/mocks/FileMock.js",
      "\\.(css|less)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "transform": {
      "^.+\\.jsx?$": "./node_modules/babel-jest",
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "./app/tests/mocks/FileTransformer.js"
    },
    "testEnvironment": "jsdom",
    "testPathDirs": [
      "./app/tests"
    ],
    "testRegex": ".*.test.js",
    "verbose": true
  }

.babelrc文件位于我的根文件夹中:

{
  "plugins": ["syntax-dynamic-import", "transform-runtime"],
  "presets": [
    [
      "es2015",
      {
        "modules": false
      }
    ],
    "react",
    "stage-0"
  ],
  "env": {
    "start": {
      "presets": [
        "react-hmre"
      ]
    }
  }
}

根据在开玩笑的入门页面上找到的文档,这是babel运作所需的一切,这很神奇。

无论如何,此测试:

import React from 'react';
import {shallow} from 'enzyme';
import Landing from '../components/Landing.component';

describe('<Landing/>', () => {
  it('should render a header to the page', () => {
    const landing = shallow(<Landing/>);
    expect(landing.find('h1').text()).toBe('This is the Landing component');
  });
});

返回:

FAIL  app/tests/Landing.component.test.js   
 ● Test suite failed to run

   /Users/shooshte/PersonalProjects/surviveJS/app/tests/Landing.component.test.js:1
   ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
                                                                                            ^^^^^^
   SyntaxError: Unexpected token import

     at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)

我究竟做错了什么?

关注者
0
被浏览
132
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

    Jest设置了env变量进行测试,因此我不得不将预设添加到.babelrc中的env设置中:

    {
      "plugins": ["syntax-dynamic-import", "transform-runtime"],
      "presets": [
        [
          "es2015",
          {
            "modules": false
          }
        ],
        "react",
        "stage-0"
      ],
      "env": {
        "start": {
          "presets": [
            "react-hmre"
          ]
        },
        "test": {
          "presets": ["es2015", "react", "stage-0"]
        }
      }
    }
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看