React Jest 示例不起作用

IT技术 javascript node.js testing reactjs jestjs
2021-05-09 22:23:39

尝试运行 Jest 测试 React 代码的示例(来自https://github.com/facebook/jest/tree/master/examples/react),我收到以下错误:

  > @ test /home/aizquier/jest/examples/react
  > jest

  Using Jest CLI v0.7.1
   FAIL  __tests__/CheckboxWithLabel-test.js 
  ● Runtime Error
  SyntaxError: /home/aizquier/jest/examples/react/__tests__/CheckboxWithLabel-test.js: Unexpected token (15:6)
  npm ERR! Test failed.  See above for more details.

测试在文件 CheckboxWithLabel-test.js 的第 15 行失败:

jest.dontMock('../CheckboxWithLabel');

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

const CheckboxWithLabel = require('../CheckboxWithLabel');

describe('CheckboxWithLabel', function() {

  it('changes the text after click', function() {

    // Render a checkbox with label in the document
    var checkbox = TestUtils.renderIntoDocument(
      <CheckboxWithLabel labelOn="On" labelOff="Off" />
    );

    var checkboxNode = ReactDOM.findDOMNode(checkbox);

    // Verify that it's Off by default
    expect(checkboxNode.textContent).toEqual('Off');

    // Simulate a click and verify that it is now On
    TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(checkbox, 'input'));
    expect(checkboxNode.textContent).toEqual('On');
  });

});

显然处理 .jsx 的预处理器不起作用。package.json 如下:

{
  "dependencies": {
    "react": "~0.14.0",
    "react-dom": "~0.14.0"
  },
  "devDependencies": {
    "react-addons-test-utils": "~0.14.0",
    "babel-jest": "*",
    "jest-cli": "*"
  },
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "scriptPreprocessor": "./node_modules/babel-jest",
    "unmockedModulePathPatterns": [
      "./node_modules/react",
      "./node_modules/react-dom",
      "./node_modules/react-addons-test-utils",
      "./node_modules/fbjs"
    ]
  }
}

我的节点是 v4.2.2,npm 是 3.3.12。

有任何想法吗??

2个回答

我遇到了同样的问题。看起来这是由最近发布的 Babel 6 引起的问题。它正在这里跟踪,希望尽快添加修复程序!

在此期间,你可以回去的早期版本babel-jest中的package.json例如,尝试^5.3.0

如果您使用的是 Babel 6,则没有默认转换,因此您需要添加一些预设。不确定您是否可以在“package.json”中执行此操作,但我添加了带有“react”和“es2015”预设的“.babelrc”文件并对其进行了排序。http://babeljs.io/docs/plugins/preset-react/