开玩笑:测试套件无法运行,语法错误:意外的令牌导入 [英] jest: Test suite failed to run, SyntaxError: Unexpected token import

查看:30
本文介绍了开玩笑:测试套件无法运行,语法错误:意外的令牌导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 package.json 文件中的 jest 配置:>

This is my jest configuration from the package.json file:

"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 文件:

And the .babelrc file located in my root folder:

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

根据在 jest 入门页面上找到的文档 这就是让 babel 发挥作用所需的一切.

According to the documentation found at the jest getting started page this is everything I need for babel to work it's magic.

不管怎样,这个测试:

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)

我做错了什么?

推荐答案

Jest 将 env 变量设置为 test,所以我不得不将我的预设添加到 .babelrc 中的 env 设置:

Jest sets the env variable to test, so I had to add my presets to the env setting in .babelrc:

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

这篇关于开玩笑:测试套件无法运行,语法错误:意外的令牌导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆