运行 通过玩笑进行测试,我在包含的 .jsx 文件中得到“意外标记”

Running test via jest, I get `Unexpected token` in included .jsx files

我正在使用 jest 和 Babel 6 并尝试 运行 包含 .jsx 文件的测试。出于某种原因,该文件未被提取为 .jsx,似乎被视为纯 js,导致包含 React 组件的行出现错误。

这是测试:

var searchPath = '../../../../../app/assets/javascripts/components/navigation/search_icon.js.jsx';
jest.dontMock(searchPath);

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils'

const SearchIcon = require(searchPath);

describe('components', () => {
  describe('SearchIcon', () => {
    it('Should dispatch an action to toggle the search bar when clicked', () => {

      var icon = TestUtils.renderIntoDocument(
        <SearchIcon labelOn="On" labelOff="Off"/>
      );

      // Smoke test - I can't even get this far :(
      expect(true).to.eq(true)

    })
  })
});

我的 package.json 在这里:

{
  "name": "fd-v5-web",
  "version": "1.0.0",
  "description": "Farmdrop mobile site",
  "dependencies": {
    "babel-preset-es2015": "^6.0",
    "babel-preset-stage-0": "^6.0",
    "babel-preset-react": "^6.0",
    "babelify": "~>7.2",
    "browserify": "~> 10.2.4",
    "browserify-incremental": "^3.0.1",
    "classnames": "~>2.1",
    "immutable": "^3.7.5",
    "lodash": "~3.9.3",
    "moment": "~2.10.3",
    "react": "^0.14.3",
    "react-redux": "^4.0.0",
    "react-dom": "^0.14.6",
    "react-tools": "^0.13.1"
  },
  "engines": {
    "node": "4.0.0",
    "npm": "2.1.x"
  },
  "devDependencies": {
    "babel-jest": "*",
    "jest-cli": "*",
    "react-addons-test-utils": "^0.14.3"
  },
  "scripts": {
    "test": "BABEL_JEST_STAGE=0 jest"
  },
  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/react",
      "<rootDir>/node_modules/react-dom",
      "<rootDir>/node_modules/react-addons-test-utils",
      "<rootDir>/node_modules/fbjs"
    ],
    "testFileExtensions": [
      "js"
    ],
    "moduleFileExtensions": [
      "js",
      "jsx",
      "json",
      "es6"
    ]
  }
}

我 运行 在命令行上 npm test

我的 .babelrc 看起来像这样:

{
  "presets": [
     "react",
     "es2015"
  ]
}

已修复。我的 .babelrc 放在了错误的文件夹中。它应该在根目录中。当我把它移到那里时,一切正常。

{
  "presets": [
     "react",
     "es2015"
  ]
}

另一个 Jest 可能抛出 Unexpected token 的地方是 @@connect 中使用时(在大多数教程中都会遇到)。在你的 package.json 文件中附加 babel-plugin-transform-decorators-legacy,运行 npm install 并确保你的 .babelrc 中有行 "presets": ["es2015", "react", "stage-0"]"plugins": ["transform-decorators-legacy"]文件。

另一个要看的地方是 any jest transform 配置。例如,可能有 JSX 转换应用于一些但不是所有源。