jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.3k stars 6.47k forks source link

Jest setup for esm modules. Error "Cannot find module" #14289

Closed Volna13 closed 1 year ago

Volna13 commented 1 year ago

I am switching from cjs to esm. I've fixed all the issues except jest running issues. He just refuses to work.

Here is datails.

/jest.config.js

export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {},
  setupFilesAfterEnv: ['./src/tests/jest.setup.ts'],
};

/src/tests/jest.setup.ts

import { stopCronJobs } from '../jobs/index.js';
import { logger } from '../utils/logger.js';
import connection from '../databases/connection.js';

beforeAll(async () => {
  logger.info('Opening a connection with a PostgreSql');
  await connection.create();
  logger.info('PostgreSql connection opened');
});

afterAll(async () => {
  await connection.close();
  stopCronJobs();
  logger.info('PostgreSql connection closed');
});

/package.json

{
  "name": "i-recreate",
  "version": "0.0.1",
  "description": "Bus info",
  "author": "Alex Dimov",
  "license": "ISC",
  "type": "module",
  "main": "./dist/server.js",
  "scripts": {
    "start": "cross-env NODE_ENV=production node --experimental-modules dist/server.js",
    "stop": "pm2 kill",
    "dev": "cross-env NODE_ENV=development nodemon",
    "build": "tsc && npx tsc-alias",
    "build:watch": "tsc -w && npx tsc-alias",
    "test": "cross-env NODE_ENV=test NODE_OPTIONS=--experimental-vm-modules jest --forceExit --detectOpenHandles --silent --runInBand",
    "lint": "eslint --ext .ts src/",
    "lint:fix": "npm run lint -- --fix",
    "seed": "node dist/databases/seeds/database.seeder.js",
    "build-and-seed": "npm run build && node dist/databases/seeds/database.seeder.js",
    "dev:debug": "nodemon --inspect",
    "typeorm:cli": "typeorm-ts-node-esm",
    "migration-generate": "npm run typeorm:cli -- migration:generate -d src/configs/data-source.ts src/databases/migrations/${npm_config_name:?}",
    "migration-run": "npm run typeorm:cli -- migration:run -d src/configs/data-source.ts",
    "migration-run-local-test": "cross-env NODE_ENV=test-local npm run typeorm:cli -- migration:run -d src/configs/data-source.ts",
    "migration-revert": "npm run typeorm:cli -- migration:revert -d src/configs/data-source.ts"
  },
  "dependencies": {
    "@types/faker": "^5.5.3",
    "@types/geojson": "^7946.0.10",
    "@types/multer": "^1.4.7",
    "@types/node-cron": "^3.0.7",
    "adminjs": "^7.0.6",
    "axios": "^1.4.0",
    "bcrypt": "^5.0.1",
    "body-parser": "^1.20.2",
    "class-transformer": "^0.4.0",
    "class-validator": "0.14.0",
    "compression": "^1.7.4",
    "config": "^3.3.6",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "cross-env": "^7.0.3",
    "dotenv": "^8.2.0",
    "envalid": "^7.1.0",
    "express": "^4.17.1",
    "express-validator": "^6.10.1",
    "hashids": "^2.3.0",
    "helmet": "^4.5.0",
    "hpp": "^0.2.3",
    "i18next": "^23.1.0",
    "jest": "^29.5.0",
    "jsonwebtoken": "^9.0.0",
    "lodash": "^4.17.21",
    "moment": "^2.29.4",
    "morgan": "^1.10.0",
    "multer": "^1.4.5-lts.1",
    "node-cron": "^3.0.2",
    "nodemailer": "^6.9.2",
    "pg": "^8.11.0",
    "reflect-metadata": "^0.1.13",
    "require-dir": "^1.2.0",
    "swagger-jsdoc": "^6.2.8",
    "swagger-ui-express": "^4.6.3",
    "ts-jest": "^29.1.0",
    "ts-node": "^10.9.1",
    "typeorm": "^0.3.16",
    "typescript": "^4.9.5",
    "winston": "^3.8.2",
    "winston-daily-rotate-file": "^4.7.1"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/compression": "^1.7.2",
    "@types/config": "^3.3.0",
    "@types/cookie-parser": "^1.4.3",
    "@types/cors": "^2.8.13",
    "@types/express": "^4.17.17",
    "@types/hpp": "^0.2.2",
    "@types/jest": "^29.5.1",
    "@types/jsonwebtoken": "^9.0.2 ",
    "@types/lodash": "^4.14.195",
    "@types/morgan": "^1.9.4",
    "@types/node": "^16.16.0",
    "@types/nodemailer": "^6.4.8",
    "@types/supertest": "^2.0.12",
    "@types/swagger-jsdoc": "^6.0.1 ",
    "@types/swagger-ui-express": "^4.1.3",
    "@typescript-eslint/eslint-plugin": "^5.59.7 ",
    "@typescript-eslint/parser": "^5.59.7 ",
    "eslint": "^8.41.0",
    "eslint-config-prettier": "^8.8.0",
    "eslint-plugin-prettier": "^4.2.1",
    "faker": "^5.5.3",
    "husky": "^8.0.3",
    "kill-port": "^2.0.1",
    "lint-staged": "^13.2.2",
    "node-config": "^0.0.2 ",
    "node-gyp": "^9.3.1 ",
    "nodemon": "^2.0.22",
    "prettier": "^2.8.8 ",
    "supertest": "^6.3.3",
    "tsconfig-paths": "^4.2.0"
  }
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["ESNext", "esnext.asynciterable"],
    "typeRoots": ["node_modules/@types", "./src/types"],
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "NodeNext",
    "module": "NodeNext",
    "pretty": true,
    "sourceMap": true,
    "declaration": true,
    "outDir": "./dist",
    "allowJs": true,
    "noEmit": false,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "importHelpers": true,
    "baseUrl": "src",
    "strict": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": false,
  },
  "include": ["src/**/*.ts", "src/**/*.json", ".env"],
  "exclude": ["node_modules"]
}

Error after run npm run test

 Cannot find module '../jobs/index.js' from 'src/tests/jest.setup.ts'

    > 1 | import { stopCronJobs } from '../jobs/index.js';
        | ^
      2 | import { logger } from '../utils/logger.js';
      3 | import connection from '../databases/connection.js';
      4 |
mrazauskas commented 1 year ago

Try ts-jest-resolver.

Volna13 commented 1 year ago

Try ts-jest-resolver.

It still not work for me(ts-jest-resolver Didn't change behavior at all). I have changed jest.config.js and now i have another errors

jest.config.js

import preset from 'ts-jest/presets/index.js';

/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
  ...preset.defaultsESM,
  resolver: 'ts-jest-resolver',
  setupFilesAfterEnv: ['./src/tests/jest.setup.ts'],
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        tsconfig: 'tsconfig.json',
        useESM: true,
      },
    ],
  },
};

Error

The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

    8 const __dirname = dirname(fileURLToPath(import.meta.url));
mrazauskas commented 1 year ago

Looks like transformation issue. You are trying to use ts-jest, but it is not part of Jest. It is maintain in a separate repo. You should file the issues there.

Volna13 commented 1 year ago

Okay, just created it. If you can, please help me there.

mrazauskas commented 1 year ago

I would suggest creating a minimal reproduction repo. That would help you to understand the problem better. Also I would be easier for others to a quick look.

niftinessafoot commented 1 year ago

Ran into this today. Fixed with this Jest config property: extensionsToTreatAsEsm

Add to your jest.config.js:

extensionsToTreatAsEsm:['.ts']
mrazauskas commented 1 year ago

Thanks. Hope that helps. If not, please open new issue with minimal reproduction repo. I will close this issue, because the "Cannot find module" error (which was the initial problem) also seems to be gone.

github-actions[bot] commented 1 year ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.