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
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');
-
also requires babel-polyfill in your devDependencites: "babel-polyfill": "^6.26.0",– KevinJan 30, 2018 at 18:59
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"]
}
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.
-
Are there any resources for setting up the mocha testing framework on truffle properly ? That would be very helpful. Jul 14, 2017 at 12:49
-
4You'll need to look into using webpack and babel to transpile your tests into a version of js that Mocha understands. Here's a guide: github.com/trufflesuite/truffle/wiki/…. And here's a generic guide on using webpack and babel with Mocha: jamesknelson.com/testing-in-es6-with-mocha-and-babel-6. I accept upvotes.– dshapiroJul 14, 2017 at 13:18
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