使用babel-jest进行开玩笑但仍会出现语法错误

时间:2015-11-26 21:20:26

标签: reactjs babeljs jestjs

我是新手,想要测试我的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 |     );

2 个答案:

答案 0 :(得分:3)

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

{
  "presets": ["react"]
}

npm test 应该可以正常工作。

答案 1 :(得分:-1)

npm install react-addons-test-utils babel-preset-es2015 babel-preset-react --save-dev

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