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.

Basic Setup

BabelJS Preset

First of all make sure there is a working BabelJS configuration in your project. If you've started from scratch this might not be the case. You need to have installed a proper preset of BabelJS supporting ES6 modules:

npm i -D babel-preset-env

Next put a file .babelrc in your project folder consisting this information:

{ "preset": ["env"] }

Integrate Mocha with BabelJS

Next install dependencies babel-register and cross-env.

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

from CLI.

Configuring WebStorm

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.

Go back