SyntaxError: Unexpected token static

HappyCry picture HappyCry · Jan 15, 2016 · Viewed 10.9k times · Source

I'm currently trying to evaluate different testing frameworks that work with React, and it turns out that Jest is on my list. However, I'm trying to use static properties outlined here: https://github.com/jeffmo/es-class-fields-and-static-properties.

So, I took the tutorial that is given on the Jest homepage, and added a static propTypes property, my code looks like this:

import React from 'react';

class CheckboxWithLabel extends React.Component {

  static defaultProps = {}

  constructor(props) {
    super(props);
    this.state = {isChecked: false};

    // since auto-binding is disabled for React's class model
    // we can prebind methods here
    // http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding
    this.onChange = this.onChange.bind(this);
  }

  onChange() {
    this.setState({isChecked: !this.state.isChecked});
  }

  render() {
    return (
      <label>
        <input
          type="checkbox"
          checked={this.state.isChecked}
          onChange={this.onChange}
        />
        {this.state.isChecked ? this.props.labelOn : this.props.labelOff}
      </label>
    );
  }
}

module.exports = CheckboxWithLabel;

When I run the tests (npm test or jest), It throws the following error:

➜  jest            
Using Jest CLI v0.8.2, jasmine1
 FAIL  __tests__/CheckboxWithLabel-test.js 
● Runtime Error
SyntaxError: Desktop/jest/examples/react/CheckboxWithLabel.js: Unexpected token (5:22)

My package.json file looks like this:

{
  "dependencies": {
    "react": "~0.14.0",
    "react-dom": "~0.14.0"
  },
  "devDependencies": {
    "babel-jest": "*",
    "babel-preset-es2015": "*",
    "babel-preset-react": "*",
    "jest-cli": "*",
    "react-addons-test-utils": "~0.14.0"
  },
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "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"
    ],
    "modulePathIgnorePatterns": [
      "<rootDir>/node_modules/"
    ]
  }
}

Any ideas on what I'm missing here?

Thanks.

Answer

Felix Kling picture Felix Kling · Jan 16, 2016

Any ideas on what I'm missing here?

Class properties are neither part of the es2015 nor the react preset.

You have to load the plugins that handles class properties:

npm install babel-plugin-transform-class-properties babel-plugin-syntax-class-properties

And in your .babelrc file (next to existing plugins or presets):

"plugins": [
   "syntax-class-properties",
   "transform-class-properties"
]