Blog

Setup and debug Jest to use ES6 imports in Node v12.x.x

Published:

The problem:

Or you may just be getting this error:

Test suite failed to run / This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

In typical Node/Javascript fashion, there are endless possible configurations and pitfalls.

The solution

We are going to:


Installation

First, install Jest:

npm install jest --save-dev

Because Jest cannot understand import, we need to transpile our code. We'll use Babel to do that.

npm install @babel/core @babel/preset-env --save-dev

Configuration

You do not need a jest.config.js file; the default options are fine. You do, however, need a Babel config file.

Here is the pitall: Babel requires the config file to be named babel.config.cjs rather than a babel.config.js file when dealing with the module config (i.e. when your package.json file has the setting "type": "module", which I assume it does if you are using the import statement). Props go to user tksilicon on Stackoverflow for finding this solution.

So, the following file in the root directory of your project.

babel.config.cjs:

module.exports = {
	presets: [
		[
			"@babel/preset-env",
			{
				useBuiltIns: "usage",
				corejs: 3,
				debug: false,
			},
		],
	]
};

Adding debugging

The best way to add debugging in VSCode is to use a plugin which gives you the "Run" and "Debug" buttons above each test.

I recommend the Jest Test Explorer which adds a Visual Studio-esque panel listing all your tests:

...however, there are many plugins in the VSCode marketplace that do something similar. These plugins do the leg-work of calling the Jest CLI and specifying the exact file and test that you want to run or debug.

Conclusion

And that is it. No need for babel-jest, no complicated .vscode/launch.json file adding the --experimental-modules flag. It's simple when you know.

Given the popularity of using ESM imports, I am surprised that getting this set up was such a headache. No one resource described this process very well.