Trying ES6 style import gives 'Cannot use import statement outside a module'
The easiest way to run Mocha tests written in ES6 is compiling them on-the-fly using Mocha --require @babel/register
option (see https://github.com/mochajs/mocha/wiki/compilers-deprecation#what-should-i-use-instead-then). Of course, you need to make sure to install the corresponding modules and set up the .babelrc
accordingly
package.json:
"dependencies": { "@babel/cli": "^7.7.4", "@babel/core": "^7.7.4", "@babel/preset-env": "^7.7.4", "@babel/register": "^7.7.4",...}
.babelrc:
{ "presets": [ [ "@babel/preset-env" ] ]}
See also https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei
I had the same problem when updating one of my ts libraries to es6 modules instead of commonjs. After the change in the tsconfig.json my npm run test
produced the mentioned error.
import chai from 'chai'^^^^^^SyntaxError: Cannot use import statement outside a module
I solved it without babel by adding an own tsconfig file just for testing.
tsconfig.testing.json
{ "compilerOptions": { "module": "commonjs", "target": "es6" }, "include": ["**/*.spec.ts"]}
To run the tests via script in package.json
"test": "cross-env TS_NODE_PROJECT=\"tsconfig.testing.json\" mocha -r ts-node/register src/**/*.spec.ts",
(cross-env to set the env variable os independent)
I was able to get this working by adding a .mocharc.yaml file at the source of my project with the following:
require: '@babel/register'
source: https://github.com/mochajs/mocha-examples/tree/master/packages/babel