Tuesday, February 6, 2018

ES6, Jest, and Webstorm: Oh My! Or, fixing 'unexpected token import'

What happens when society tries to rely on arguably one of the world's worst technologies? Fragmentation.

Javascript is beyond fragmented. In any given project, you may be piecing together chunks of react, babel, gulp, webstorm, jest, jsx, webpack, less... The list goes on. All of these parts rarely play together nicely, too.

That led to a giant headache for me and thousands of other Jest users. We wrote up a file in ES6 syntax (to un-worsify the world's worst technology), and wrote an index.test.js file only to find that, oh no:

UNEXPECTED TOKEN 'import'

What's Going on?
What exactly a module is... is not exactly known. Babel isn't putting it into a format that jest is able to properly test. To fix this issue with a very barebones project structure, you need to:

yarn add jest-cli babel babel-core babel-plugin-transform-es2015-modules-commonjs 

This will install everything you need to run Jest, including the babel plugin that turns these modules into a readable format.

package.json
"jest": {
  "testEnvironment": "jsdom"},
"babel": {
  "presets": [
    "es2017"  ]
},
"scripts": {
  "test": "jest --no-cache --verbose"}

.babelrc
{
  "presets": ["es2017"],  "plugins": ["transform-es2015-modules-commonjs"]
}
Good! You now have everything that you need to do your yarn test or npm test with ES6 modules!

Take it a step further: Debug in Webstorm
Wouldn't it be absolutely awful to run a test, and have it say "cannot call function .getName of undefined"? Well, thankfully with this configuration we can properly debug.

Webstorm comes with a debug configuration called Jest. These are the settings you want:



You're all set!
Just set a breakpoint in your es6 code, and select the bug icon on the main webstorm toolbar.

babel will turn the es6 into an understandable Javascript (es3-5), the transform-es2015-modules-commonjs will turn those modules into modules that jest and browsers can understand, and the jest run configuration can talk to node over the V8 debugging protocol to let you set breakpoints.

It's kind of amazing what this hodgepodge of technology can accomplish!