0

I defined an alias in package.json:

  "_moduleAliases": {
    "@microservices": "./microservices",
  }

When I use imports such as:

import ClassName from "@microservices/service_name/class_name";

it works when I launch the program.

However, this same imoprt fails to work when I run unit tests. I use Mocha test runner and when I run:

node_modules/mocha/bin/_mocha --inspect --opts=test/mocha.opts test/microservices/service_test.ts

I get the error:

Error: Cannot find module '@microservices/south_state_detector/app/base_task' Require stack: C:\MyProject\test\microservices\service_name\class_name.ts

It means that when running it from a unit test, mocha takes "service_name\class_name.ts" with relation to C:\MyProject\test and not from C:\MyProject.

Do you know how to resolve it so I can safely use module aliases also when running tests?

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183
  • Have you tried putting `require("module-alias/register")` (or the equivalent import) before your tests? – Half Aug 13 '23 at 16:21
  • @Half I tried it after reading your comment. It didn't help – CrazySynthax Aug 13 '23 at 20:08
  • That's my only easy idea — in this case I expect you'll need help from someone familiar with the workings of both mocha and module-alias packages, which may be difficult to find. You may want to edit your question and particularly the title, to mention you're using `mocha` and `module-alias` packages more clearly, to improve your chances of one of them finding this. If you do end up figuring this out on your own, please consider writing an answer to your own question, since I'd interested to learn more about how this works. – Half Aug 13 '23 at 20:37

0 Answers0