Petra Barus
Petra Barus

Reputation: 4013

Error "Unexpected token" when run mocha against JSX syntax

I am kind of new to Javascript programming. I tried writing a test for a script with JSX format, but somewhat it fails with Unexpected token.

Here's the test code, I haven't write any test yet.

//Rectangle.js
let assert = require('chai').assert,
    path = require('path');

import Rectangle from './Rectangle';

And here's the code that needs to be tested

//Rectangle.jsx
import React from 'react';

class Rectangle extends React.Component {
    render() {
       return <h1>Hello, {this.props.name}</h1>;
    }
}

Here's the error

SyntaxError: Rectangle.jsx: Unexpected token (5:11)
  3 | class Rectangle extends React.Component {
  4 |   render() {
> 5 |     return <h1>Hello, {this.props.name}</h1>;
    |            ^
  6 |   }
  7 | }

Here's the mocha command that I got from some articles nyc mocha --compilers js:babel-core/register Rectangle.js.

I also uploaded the code on github (link), so you could see the installed dependencies.

How should I fix this? Is there a step that I missed?

Upvotes: 1

Views: 944

Answers (2)

wahahab
wahahab

Reputation: 36

I think you may need custom compiler to help you compile jsx code.

You can see the example here: Mocha-react repo.

Upvotes: 1

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to add react preset to you babel config inside package.json

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

Upvotes: 2

Related Questions