allenhwkim / ngentest

Angular6+ Unit Test Generator For Components, Directive, Services, and Pipes
https://ngentest.github.io
MIT License
144 stars 60 forks source link

cannot find module using alias #49

Closed Viktor-Bredihin closed 1 year ago

Viktor-Bredihin commented 3 years ago

Screenshot from 2021-05-11 21-35-14 Screenshot from 2021-05-11 21-34-49 When I run ngtest command for any file, which use import from alias - I get Cannot find module error

allenhwkim commented 3 years ago

ngentest generates tests by looking at your code, a single file, not all your app.

This happens when the test generator, which has an isolated environment, tries to compile your code, which means it can't find your module.

As you seen in README.md, try using replacements. This does not mean replacing your code. It just temporarily replace the code in memory to avoid compile error from Typescript to Javascript.

  // faking import for errorenous lib.
  replacements: [
    { from: '@shared/\\.*', to: '' }
  ]

image

Viktor-Bredihin commented 3 years ago

@allenhwkim not sure how it can help, with replacement I have this error { Error: Cannot find module 'model/financial-year/financial-year' If I change import { FinancialYear } from '@shared/model/financial-year/financial-year'; to import { FinancialYear } from '../app/shared/model/financial-year/financial-year'; it works fine, but I can't replace all imports

should I add all my aliases to replacements like this? { from: '@shared/\.*', to: 'src/app/shared' }, ... it doesn't work as well, I guess I need some kind of basePath here

I also tried https://www.npmjs.com/package/module-alias, but got another error

I don't really understand why it gives me an error when I try to import model, but works fine when I import service

Also tried one of your answers here https://github.com/allenhwkim/ngentest/issues/45, but got error TypeError [ERR_INVALID_ARG_VALUE]: The argument 'id' must be a non-empty string. Received '' so I guess it's not an option anymore

allenhwkim commented 3 years ago

try this this in your config.

  replacements: [
    { from: '@shared/\\.*', to: '' }
  ]
SETI-At-Home commented 3 years ago

@Viktor-Bredihin temporarily change url from @shared/... to ../../shared/ . Somehow ngentest doesn't recognize @ paths or src/app/.

allenhwkim commented 3 years ago

Please share your minimal .ts code, so that I can reproduce your error.

Any import path set by your app must be replaced because ngentest runs on its own isolated environment.

  replacements: [
    { from: '@shared/\\.*', to: '' },
    { from: 'model/\\.*', to: '' },
  ]