13

I get an "SyntaxError: Unexpected token import" error when I do 'truffle test'. I am trying to import a function declared in another file into the java-script test file. I have been searching about this issue for quite sometime and couldn't find any solution. Is this an issue with mocha testing on truffle ?

4 Answers 4

20

All it needed was to add a package.json file to the project directory with some babel dependencies and doing an 'npm install'. Also, adding a '.babelrc' file to the truffle project directory. Finally, adding some requires to truffle.js file.

package.json file

{
  "name": "game-token",
  "devDependencies": {
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-stage-2": "^6.24.1",
    "babel-preset-stage-3": "^6.17.0",
    "babel-polyfill": "^6.26.0",
    "babel-register": "^6.23.0"
  }
}

.babelrc file

{
  "presets": ["es2015", "stage-2", "stage-3"]
}

requires in truffle.js

require('babel-register');
require('babel-polyfill');
1
  • also requires babel-polyfill in your devDependencites: "babel-polyfill": "^6.26.0",
    – Kevin
    Jan 30, 2018 at 18:59
6

I tried i_robot's solution, and it almost* worked, I had to add:

require('babel-register')({
  ignore: /node_modules\/(?!zeppelin-solidity)/
});
require('babel-polyfill');

at the top of my truffle.js. The ignore field is important!! In addition to adding babel-polyfill in my package.json dependencies:

  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-stage-2": "^6.24.1",
    "babel-preset-stage-3": "^6.17.0",
    "babel-register": "^6.23.0",
    "bignumber.js": "^5.0.0",
    "bluebird": "^3.5.1",
    "lodash": "^4.17.4",
    "zeppelin-solidity": "1.6.0"
  }

.babelrc file

{
  "presets": ["es2015", "stage-2", "stage-3"]
}
1

If you aren't using es6 javascript, you can't use the import keyword. If you are using es6, maybe you don't have mocha set up correctly to understand or transpile down to es5 before you run your tests.

2
0

I found it easier to use the require method.

src/utils.js:

exports.a = 3;

test/foo/testfile.js:

// Note the relative path from the current test file.
const utils = require('../../src/utils.js');
console.log(utils.a); // 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.