Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: Cannot use import statement outside a module

I got an error when I run test using Jest, I tried to fix this error for 2 hours. But, I couldn't fix it. My module is using gapi-script package and error is occurred in this package. However, I don't know why this is occurred and how to fix it.

jest.config.js

module.exports = {
  "collectCoverage": true,
  "rootDir": "./",
  "testRegex": "__tests__/.+\\.test\\.js",
  "transform": {
    '^.+\\.js?$': "babel-jest"
  },
  "moduleFileExtensions": ["js"],
  "moduleDirectories": [
    "node_modules",
    "lib"
  ]
}

babel.config.js

module.exports = {
  presets: [
    '@babel/preset-env',
  ]
};

methods.test.js

import methods, { typeToActions } from '../lib/methods';

methods.js

import { gapi } from "gapi-script";
...

Error Message

C:\haram\github\react-youtube-data-api\node_modules\gapi-script\index.js:1 ({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import { gapi, gapiComplete } from './gapiScript';

SyntaxError: Cannot use import statement outside a module

What is wrong with my setting?

like image 521
undefined Avatar asked Jan 13 '20 02:01

undefined


1 Answers

As of this writing, Jest is in the process of providing support for ES6 modules. You can track the progress here:

https://jestjs.io/docs/en/ecmascript-modules

For now, you can eliminate this error by running this command:

node --experimental-vm-modules node_modules/.bin/jest

instead of simply:

jest

Be sure to check the link before using this solution.

like image 154
Seth Avatar answered Sep 21 '22 15:09

Seth