Using ES Modules with TS, and Jest testing(cannot use import statement outside module)

21 views Asked by At

I am trying out testing for the first time since I have started my journey with Express and TS. I decided to do some testing on a new project with Jest, but I want to use import/exports instead of require...but now jest is complaining that I cant use import statement outside a moduel. I looked at different solutions on here, but I might have messed up something previously and thats why its not working for me. Currently I have these files:

package.json:

 {
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "type": "module",
  "scripts": {
    "test": "jest",
    "start": "node src/index.ts",
    "dev": "nodemon src/index.ts",
    "build": "tsc"
  },
  "keywords": [],
  "author": "Gabor Adorjani <[email protected]>",
  "license": "ISC",
  "devDependencies": {
    "@types/express": "^4.17.21",
    "@types/jest": "^29.5.12",
    "@types/node": "^20.11.30",
    "bcrypt": "^5.1.1",
    "cors": "^2.8.5",
    "crypto": "^1.0.1",
    "express": "^4.19.1",
    "jest": "^29.7.0",
    "jsonwebtoken": "^9.0.2",
    "mongodb": "^6.5.0",
    "mongoose": "^8.2.3",
    "nodemon": "^3.1.0",
    "ts-jest": "^29.1.2",
    "typescript": "^5.4.3",
    "uuid": "^9.0.1"
  },
  "dependencies": {
    "@types/bcryptjs": "^2.4.6",
    "@types/supertest": "^6.0.2",
    "bcryptjs": "^2.4.3",
    "crypto-js": "^4.2.0",
    "dotenv": "^16.4.5",
    "express-rate-limit": "^7.2.0",
    "http": "^0.0.1-security",
    "http-proxy-middleware": "^2.0.6",
    "mongodb-memory-server": "^9.1.8",
    "supertest": "^6.3.4"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "sourceMap": true,
    "resolveJsonModule": true,
    "outDir": "dist",
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "files": ["types.d.ts"],
  "ts-node": {
    "esm": true,
    "compiler": "typescript"
  }
}
0

There are 0 answers