Cannot use import stmt outside a module" - Jest

I am getting the following error when running tests with Jest:

SyntaxError: Cannot use import statement outside a module

This occurs when running a test file that imports a module using the gapi-script package:

methods.test.js

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

methods.js

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

My jest.config.js and babel.config.js files are configured as follows:

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',
  ]
};

I have spent 2 hours trying to fix this error but have been unsuccessful. Why is this occurring and how can I fix it?

The error “SyntaxError: Cannot use import statement outside a module” occurs because Node.js does not support ES modules (import/export) by default. To fix this, you can use Babel to transpile your code.

To resolve the issue, follow these steps:

  1. Install the necessary dependencies:
npm install --save-dev @babel/preset-env babel-jest
  1. Update your babel.config.js file to include the @babel/preset-env preset:
module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }]
  ]
};
  1. Update your jest.config.js file to use the babel-jest transformer:
module.exports = {
  "collectCoverage": true,
  "rootDir": "./",
  "testRegex": "__tests__/.+\\.test\\.js",
  "transform": {
    '^.+\\.js?$': "babel-jest"
  },
  "moduleFileExtensions": ["js"],
  "moduleDirectories": [
    "node_modules",
    "lib"
  ]
}
  1. Try running your tests again. The error should be resolved now.

The updated configuration will transpile your code using Babel before running the tests, allowing you to use ES modules.