Using ES6 Modules in Unit Tests of a WebPack-based VueJS Project
by Thomas Urban
In a VueJS project built with WebPack template some manual setup is required to get MochaJS tests work with ES6 modules. In addition this is possible in context of WebStorm running single tests or suites of tests, too.
First install dependencies
npm i -D babel-register cross-env
The first module is required to integrate BabelJS with MochaJS. The second one is a simple tool enabling provision of environment variables in
scripts section of
package.json file working on Linux/Mac as well as on Windows.
Adjust or add script for invoking MochaJS in
package.json file to read like this:
"test": "cross-env NODE_ENV=test mocha --require babel-register path/to/your/tests/**/*.js"
This will enable support for ES6 modules in test files when running all tests via
npm run test
In WebStorm you need to adjust runtime configuration of Mocha (2) in section containing default configurations (1). Add environment variable
NODE_ENV with value
test (3) and enter
--require babel-register in field labelled "Extra Mocha options" (4).
Next remove all existing Mocha runtime configurations so the default is applied in all upcoming invocations of MochaJS based tests.