Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - Jest not preprocessing my JSX

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"] }


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...