【问题标题】:Why Jest is throwing "Unexpected token ILLEGAL" when testing React component?为什么 Jest 在测试 React 组件时会抛出“Unexpected token ILLEGAL”?
【发布时间】:2015-04-02 14:43:34
【问题描述】:

我跟着Jest - React tutorial 测试了一个 React 组件。

不幸的是,Jest 抛出:

SyntaxError: /Users/mishamoroshko/react-playground/src/search-panel/questions/__tests__/questions-test.js: /Users/mishamoroshko/react-playground/src/search-panel/questions/questions.js: Unexpected token ILLEGAL
at Contextify.sandbox.run (/Users/mishamoroshko/react-playground/node_modules/jest-cli/node_modules/jsdom/node_modules/contextify/lib/contextify.js:12:24)
at JSDomEnvironment.runSourceText (/Users/mishamoroshko/react-playground/node_modules/jest-cli/src/JSDomEnvironment.js:108:22)
at Object.runContentWithLocalBindings (/Users/mishamoroshko/react-playground/node_modules/jest-cli/src/lib/utils.js:341:23)

重现:

  1. git clone git@github.com:SEEK-Jobs/react-playground.git
  2. cd react-playground
  3. npm install
  4. npm test

有什么想法吗?


更新 1:

不知道是不是Jest不知道ES6的问题,需要用6to5-jest

有没有办法在 package.json 中指定 2 个预处理器?

"jest": {
  "rootDir": "src",
  "scriptPreprocessor": "../preprocessor.js",
  "unmockedModulePathPatterns": [
    "../node_modules/react"
  ]
}

【问题讨论】:

标签: reactjs jestjs reactjs-testutils


【解决方案1】:

确实,添加6to5-jest 解决了这个问题。

这是我在 Jest 中实现多个 scriptPreprocessors 的方法:

// preprocessor.js

var ReactTools = require('react-tools');
var to5 = require('6to5-jest').process;

module.exports = {
  process: function(src, filename) {
    return ReactTools.transform(to5(src, filename));
  }
};

如果您有更好的方法来实现这一点,请发表评论。

【讨论】:

  • ReactTools.transform(src, {harmony: true}) 将为您提供 ES6 的一些更简单的部分(箭头函数、类等)。此外,6to5 理解 JSX 并针对 react 的 jsx 测试运行。除非我遗漏了什么,否则 ReactTools.transform 在你的代码中只是一个非常昂贵的 noop。
  • @FakeRainBrigand 你是对的!我删除了ReactTools.transform,一切正常。非常感谢您的提示!
猜你喜欢
  • 1970-01-01
  • 2020-01-15
  • 2022-06-16
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
相关资源
最近更新 更多