Jest not preprocessing my JSX

2019-04-04 20:29发布

I am following the Jest tutorial to test a react component and am running into preprocessing issues with my jsx. I assume the error is due to preprocessing, the error message is not very helpful. Googling shows similar errors with older versions of react/jest that were fixed by including the /** @jsx React.DOM */ docblock which as far as I can tell was fixed.

When I run my test:

Using Jest CLI v0.8.0, jasmine1
 FAIL  spec/MyComponent_spec.js
Runtime Error
SyntaxError: /Users/asdf/react/stuff-react/spec/MyComponent_spec.js: Unexpected token (13:6)
npm ERR! Test failed.  See above for more details.

The line in question is the one that should be rendering my component:

jest.dontMock('../src/MyComponent');

let React = require('react');
let ReactDOM = require('react-dom');
let TestUtils = require('react-addons-test-utils');

const MyComponent = require('../src/MyComponent');

describe('MyComponent', function(){
  it('render', function(){

    var myComponent = TestUtils.renderIntoDocument(
      // This is the line referenced in the test error
      <MyComponent />
    )
    var myComponentNode = ReactDOM.findDOMNode(myComponent);

    expect(myComponentNode.textContent).toEqual('hi');
  });
});

I thought my package.json was responsible for telling jest to preprocess that file?

 "scripts": {
    "test": "jest"
  },
  "jest": {
    "testDirectoryName": "spec",
    "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"
    ]
  },

My component:

import React from 'react';

class MyComponent extends React.Component({
  render () {
    return (
      <div>
        hi
      </div>
    )
  }
});

export default MyComponent;

2条回答
beautiful°
2楼-- · 2019-04-04 21:27

I think you may just need to add the testFileExtensions and testFileExtensions to the jest section of your package.json.

See the README.md of babel-jest:

https://github.com/babel/babel-jest

查看更多
对你真心纯属浪费
3楼-- · 2019-04-04 21:29

Using a .bablerc file in the project root directory fixed it for me.

I was not using a .babelrc file while developing because I defined my presets in the webpack configuration file. But it turns out that when you run the unit test with jest, then jest is not aware of this presets as it does not know about webpack. So simply adding a .babelrc file with the presets should solve the issue for you too.

Contents of .babelrc:

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

查看更多
登录 后发表回答