0

I am writing integration tests for Javascript code using Jest. But I am seeing SyntaxError: Cannot use import statement outside a module. Its been quiet sometime I have been on this and this issue is killing my time! I have all the configuration in place but still this isn't working. Also followed the steps mentioned here but in vain.

Error Details:

C:xx\node_modules\node-fetch\src\index.js:9
import http from 'node:http';
^^^^^^
SyntaxError: Cannot use import statement outside a module

And when I checked index.js of node-fetch it has has import statements.

Project Structure:

-resources
   |__package.json
   |__babel.config.js
   |__node_modules
   |__static
          |__integration-tests
                     |__somescript.int.test.js 

babel.config.js:

module.exports ={
    presets: ['@babel/preset-env'],
    plugins: [
        "@babel/plugin-transform-modules-commonjs",
        "@babel/plugin-transform-runtime",
    ]
}

package.json:

{
  "name": "some-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest --testRegex='script/integration-tests/.*(int-test))\\.js?$'"
  },
  "devDependencies": {
    "jest": "^28.1.3",
    "node-fetch": "^3.2.10",
    "uglify-js": "3.16.2",
    "@babel/core": "^7.19.0",
    "@babel/cli":^7.18.10,
    "@babel/plugin-transform-modules-commonjs": "^7.18.6",
    "@babel/plugin-transform-runtime": "^7.18.10",
    "@babel/preset-env": "^7.19.0",
    "babel-jest": "^29.0.2"
  }
}

validator.js(Javascript):

import {fetch} from 'node-fetch';

function validate(){
    fetch(SOME_UENDPOINT_URL, {
        method: 'GET',
        mode: 'cors',
        credentials: 'include',
        headers:{
            'content-type': 'application/json',
        }
    }).then(response => {
        return response;
    }).then(data => {
        
    });     
}

validator-int.test.js(Jest script)

const{validate} = require('../scripts/validator');

describe('User validation', () => {
     test('Should authenticate user', ()=>{
         validate();
         //some basic assertion follows
      });   
});

I really appreciate if some can guide me! I have been through the jest and babel documentation but those are of little to no help compared to stackoverflow!

  • `"type" : "module"` in `package.json` – Konrad Sep 06 '22 at 11:14
  • ReferenceError: module is not defined in ES module scope. This file is being treated as an ES module because it has .js extn,, This is the error I see when I add "type" : "module" – Pratap Charithra Sep 06 '22 at 14:44
  • just for reference here is my jest.config.js I am assuming the below js must be written in ES Module compatible ? module.exports = { transform: { '\\.[jt]sx?$': 'babel-jest' }, } – Pratap Charithra Sep 06 '22 at 15:40

0 Answers0