Babel-jest Doesn't Handle ES6 Within Modules


Answer :

By default any code in node_modules is ignored by babel-jest, see the Jest config option transformIgnorePatterns. I've also created a PR on your example repo, so you can see it working.

While this works, I've found it to be extremely slow in real applications that have a lot of dependencies containing ES modules. The Jest codebase has a slightly different approach to this as you can find in "babel-jest transforming dependencies" (sorry, won't let me post more than 2 URLs). This can also take much longer on Windows, see "Taking 10 seconds on an empty repo".

If doing "unit" testing, mocking is probably the better way to go.


You could try adding the transform-es2015-modules-commonjs plugin to your babel config file for testing only. Here is an example config file which tells babel to transpile modules only when in a testing environment. You can put it underneath your presets:

{   "presets": [     "react",     ["es2015", {"modules": false, "loose": true}]   ],   "env": {     "test": {       "plugins": ["transform-es2015-modules-commonjs"]     }   } } 

You can read about the plugin here:

https://www.npmjs.com/package/babel-plugin-transform-es2015-modules-commonjs

Then, when running your Jest tests on the command line specify NODE_ENV=test (you may need to add the --no-cache flag to the command the first time after making the change to the babel config because Jest caches babel output, but after that you can leave it off:

NODE_ENV=test jest --no-cache 

I learned about this issue in a React seminar by Brian Holt at Frontend Masters. https://frontendmasters.com/courses/


Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?