justkey007 / tsc-alias

Replace alias paths with relative paths after typescript compilation
MIT License
876 stars 63 forks source link

How to tsc-alias it with mocha? #207

Closed Kripu77 closed 7 months ago

Kripu77 commented 8 months ago

Hi everyone,

I'm currently working on a TypeScript project, and I've been using the tsc-alias package to manage path aliases in my TypeScript codebase. This has worked well for the application code, but I'm facing challenges when trying to set up and run tests using Mocha.

Problem:

I'd like to find a solution or guidance on how to effectively integrate tsc-alias with Mocha for running tests. Specifically, I want to ensure that Mocha recognizes and resolves the TypeScript path aliases correctly during test execution.

Current Configuration:

Here's a snippet of my tsconfig.json:

{
  "extends": "ts-node/node16/tsconfig.json",
  "ts-node": {
    // It is faster to skip typechecking.
    // Remove if you want ts-node to do typechecking.
    "transpileOnly": true,
    "files": true,

  },

 "compilerOptions": {
   "module": "commonjs",
   "esModuleInterop": true,
   "target": "es6",
   "moduleResolution": "node",
   "sourceMap": true,
   "outDir": "dist",
   "rootDir": "src",
   "declaration": true,
   "types": ["node", "mocha"],
   "skipLibCheck": true,
    "paths": {
      "@/*": ["./src/*"]
    }
 },
 "lib": ["es2015"],
 "include": ["src/"],
 "exclude": [
     "dist",
     "node_modules",
     "src/**/*.spec.ts"
   ],
}

My test script in package.json

mocha --experimental-specifier-resolution=node --loader ts-node/esm --require ts-node/register --require dotenv/config --recursive 'test/*.test.ts'"

I'm seeking advice, examples, or any information on how to configure Mocha to work with tsc-alias for testing. Are there specific steps, plugins, or configurations that I need to add to my Mocha setup?

Thank you!

Kripu77 commented 7 months ago

Hi Guys, I was able to solve it by using tsconfig-paths/register I have my test script updated as:

"test:unit": "mocha --experimental-specifier-resolution=node --loader ts-node/esm --require ts-node/register --require tsconfig-paths/register --require dotenv/config --recursive 'test/*.test.ts'",