【问题标题】:use babel-jest for jest but still get syntax error使用 babel-jest 开玩笑,但仍然出现语法错误
【发布时间】:2016-03-01 01:16:10
【问题描述】:

我是 jest 的新手,想测试我的 react.js 应用程序。 我正在关注一本书,开玩笑的 React.js Essentials。

这是我的测试代码,Button-test.js

jest.dontMock('../Button.react');

describe('Button component', function () {
  it('calls handler function on click', function () {
    var React = require('react');
    var TestUtils = require('react-addons-test-utils');
    var Button = require('../Button.react');
    var handleClick = jest.genMockFunction();

    var button = TestUtils.renderIntoDocument(
      <Button handleClick={handleClick}/>
    );

    var buttonInstance =
      TestUtils.findRenderedDOMComponentWithTag(button, 'button');

    TestUtils.Simulate.click(buttonInstance);
    expect(handleClick).toBeCalled();
    var numberOfCallsMadeIntoMockFunction =
      handleClick.mock.calls.length;
    expect(numberOfCallsMadeIntoMockFunction).toBe(1);
  });
});

这是我的 package.json

{
  "name": "snapterest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-jest": "^6.0.1",
    "babelify": "^6.2.0",
    "browserify": "^12.0.1",
    "gulp": "^3.9.0",
    "jest-cli": "^0.8.0",
    "vinyl-source-stream": "^1.1.0"
  },
  "dependencies": {
    "react": "^0.14.0-beta3",
    "react-dom": "^0.14.0-beta3",
    "snapkite-stream-client": "^1.0.3"
  },
  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "testFileExtensions": ["es6", "js"],
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/react"
    ]
  }
}

问题是,当我运行 npm test 时,它会报告以下语法错误。我认为 babel-jest 已安装,我不知道为什么语法错误仍然存​​在。除了安装 babel-jest 我还需要做什么吗?

source/components/__tests__/Header-test.js 
● Runtime Error
SyntaxError:        
/snapterest/source/components/__tests__/Header-test.js: Unexpected token (11:6)
   9 |    
  10 |     var button = TestUtils.renderIntoDocument(
> 11 |       <Button handleClick={handleClick}/>
     |       ^
  12 |     );

【问题讨论】:

    标签: reactjs babeljs jestjs


    【解决方案1】:

    你在使用 babelify v7 吗?如果是这样,您可能已经按照here 中提到的修复方法在您的 gulpfile 中添加了 react 预设。测试也需要发生同样的事情,但由于这是单独运行的,因此您可以将其添加到项目根目录中的 .babelrc 文件中:

    {
      "presets": ["react"]
    }
    

    npm test 然后应该可以正常工作了。

    【讨论】:

    • 这解决了我的问题。只有我将"babel": { "presets": [ "react" ] } 添加到我的package.json 文件中。
    【解决方案2】:
    npm install react-addons-test-utils babel-preset-es2015 babel-preset-react --save-dev
    

    http://facebook.github.io/jest/docs/tutorial-react.html#content

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 2020-06-08
      • 1970-01-01
      • 2019-04-18
      • 2019-08-09
      • 2018-01-15
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多