Ash Ash - 1 year ago 144
Node.js Question

Unit Testing Syntax error, react, mocha

I'm attempting to set up some tests for my react app with enzyme, mocha and chai. (I'm also using webpack). I have Karma set up for my in-browser tests but i'd like to run these tests with just node.

I'm currently getting a syntax error when it tries to run the test. I'm not sure how to resolve it.

Update: I am running my tests with es6

mocha 'components/**/*.test.js' --recursive --compilers js:babel-register

The error I get is:

8 | describe('<button />', () => {
9 | it('renders something', () => {
> 10 | const wrapper = shallow(<button />)
11 | expect(wrapper)
12 | })

Answer Source

You need to set up Babel before it can handle JSX syntax.

There are two options: add the configuration to your package.json, or create a file called .babelrc that contains the configuration.

First, install babel-preset-react:

$ npm i babel-preset-react --save

Next, add the following to your package.json:

"babel": {
  "presets": [ "react" ]

(or add that object, without the "babel" key, to .babelrc)

Another preset that you may likely want to use is babel-preset-es2015, which you can add in a similar fashion (just add it to the presets array).

More documentation on Babel configuration here and here (specifically for es2015).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download