Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest es6 modules: unexpected module import

Tags:

I'm trying to test a file which needs to import an es6 module like this:

https://repl.it/HG9t/0

It seems I'm missing some configurations to make it work properly.

If you can achieve this with another unit testing framework easily, I'm interested too.

Thank you in advance for your help.

like image 768
Alphapage Avatar asked Apr 12 '17 10:04

Alphapage


People also ask

Does jest work with ES6?

Jest can be used to mock ES6 classes that are imported into files you want to test. ES6 classes are constructor functions with some syntactic sugar. Therefore, any mock for an ES6 class must be a function or an actual ES6 class (which is, again, another function). So you can mock them using mock functions.

Does jest support ES6 Import Export?

The ES6 import / export statements are not supported by default in Node version 12. Jest wants CommonJS modules, but you're using . js files.

Does jest support ESM modules?

Jest ships with experimental support for ECMAScript Modules (ESM). The implementation may have bugs and lack features. For the latest status check out the issue and the label on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still considered experimental by Node (as of version 18.8.


2 Answers

  1. Install required dependencies:

yarn add --dev babel-jest @babel/core @babel/preset-env

or

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

  1. Create babel.config.js in your main folder and paste it there:
// babel.config.js module.exports = {   presets: [     [       '@babel/preset-env',       {         targets: {           node: 'current',         },       },     ],   ], }; 
  1. Make sure all your jest settings in package.json and jest.config.js are set to default.
like image 184
Ilyich Avatar answered Sep 28 '22 19:09

Ilyich


As node does not support modules you have to compile your files using Babel. Have a look at the docs on how to configure Jest and Babel

like image 29
Andreas Köberle Avatar answered Sep 28 '22 20:09

Andreas Köberle