SyntaxError: Unexpected reserved word on running m

2019-07-08 04:18发布

问题:

On running the enzyme test by using mocha. I am getting the error

(function (exports, require, module, __filename, __dirname) { import React fro ^^^^^^

SyntaxError: Unexpected reserved word

I have the below-given test script in my test file

import React from 'react';
import { assert } from 'chai';
import { render } from 'enzyme';
import Book from '../src/Book';

describe("Book", () => {
it("render text", () => {
const wrapper = render(<Book author="Dan Abramov" title="Redux and ReactJS" />);

assert.equal(wrapper.text(), 'Redux and ReactJS by Dan Abramov');
});
});

I have tried to replace import with require, did not work. It would be wonderful if someone give a helping hand to figure out the issue.

EDIT I am including the package.json file below,

{
"name": "test-client",
"version": "0.0.1",
"description": "test companies client.",
"repository": "https://github.com/Test/test-client",
"main": "js/app.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "mocha"
},

"dependencies": {
"classnames": "2.2.*",
"clone": "^1.0.2",
"es5-shim": "4.1.*",
"es6-object-assign": "1.0.*",
"es6-promise": "3.0.*",
"flux": "^2.1.1",
"font-awesome": "^4.5.0",
"form-data": "^1.0.0-rc3",
"hashids": "^1.0.2",
"howler": "^1.1.29",
"isomorphic-fetch": "^2.2.1",
"js-cookie": "^2.1.0",
"json3": "3.3.*",
"keymirror": "0.1.*",
"normalize.css": "^4.0.0",
"react": "^15.0.1",
"react-addons-create-fragment": "^15.0.1",
"react-dnd": "^2.1.4",
"react-dnd-html5-backend": "^2.1.2",
"react-dom": "^15.0.1",
"react-infinite": "^0.9.2",
"react-paginate": "^1.0.4",
"react-tooltip": "^2.0.0",
"socket.io-client": "1.3.*",
"twemoji": "^2.0.5",
"unorm": "^1.4.1"
},
"devDependencies": {
"browserify": "^6.2.0",
"catw": "^1.0.1",
"dockerode": "^2.0.4",
"dotenv": "^2.0.0",
"envify": "^3.4.0",
"gulp-awspublish": "^3.0.2",
"less": "^2.6.1",
"reactify": "^0.15.2",
"watchify": "^3.4.0"
},
"browserify": {
"transform": [
  "reactify",
  "envify"
]
},
"scripts": {
"start-css": "catw -c 'lessc -' 'css/src/*.less' -o css/bundle.css -v",
"start-js": "watchify -o js/bundle.js -v -d js/app.js",
"start": "npm run start-css & npm run start-js"
},
"author": "Test"
}

回答1:

Your test uses ES2015, for which you require a transpiler like Babel.

To get this working with Mocha, you first need to install a few packages:

$ npm install --save-dev babel-core babel-preset-es2015 babel-preset-react

Next, add the following to your package.json:

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

Or, if you don't have a package.json, create a file called .babelrc in the working directory, containing the following:

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

Lastly, tell Mocha to use the Babel transpiler:

$ mocha --compilers js:babel-core/register test.js