8

在 Gitlab-CI 环境中,我们的 Jest 测试 2 以Cannot find module.
奇怪的是它可以在我的本地 Win10 机器上运行——即使我在类似的 docker-container ( node 12.12.0) 中运行测试。

这是控制台输出:

FAIL apps/server/src/domain/dashboard/permission-group.service.spec.ts
Test suite failed to run
  Cannot find module '@cm/utils-server' from 'license.service.ts'
     9 |   isLicenseFileContent,
    10 |   LicenseStatus,
  > 11 |   parseLicenseInfo
       |                   ^
    12 | } from '@cm/license-shared';
    13 | import { ExitCode } from '../../util/exit-codes';
    14 | import { readFile } from '@cm/utils-server';
    at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)
    at Object.<anonymous> (src/domain/license/license.service.ts:11:24)

我不确定如何正确解释此输出:

  1. permission-group.service.spec.ts: 这是失败的测试
  2. Cannot find module '@cm/utils-server' from 'license.service.ts':
    好的,测试或者它的一些依赖,使用license.service.ts并在license.service.ts文件'@cm/utils-server'中找不到模块。
  3. 错误指示符 ( >at parseLicenseInfo) 是什么意思?
    • 这是用于导入@cm/license-shared- 不是@cm/utils-server如 2 中的错误消息所示
    • @cm/utils-server也是导入的,但第 14 行下面有 2 行:所以这可能只是一个开玩笑的错误吗?
4

2 回答 2

6

I just had this issue and searched for some solutions. Found this site which gave a clue about what could be done: to configure Jest's moduleNameMapper property.

So, reading the documentation I found this solution:

  1. Open the tsconfig.json and jest.config.js files (or equivalent)

  2. In tsconfig.json, find your absolute paths definition. My configuration looks like this:

"paths": {
    "@modules/*": ["modules/*"],
    "@config/*": ["config/*"],
    "@shared/*": ["shared/*"]
}
  1. In the jest.config.json, find and uncomment the moduleNameMapper property and start to translate your TS absolute paths into the Jest mapper syntax. Sounds complicated, but it isn't:
moduleNameMapper: {
    "@modules/(.*)": "<rootDir>/src/modules/$1",
    "@config/(.*)": "<rootDir>/src/config/$1",
    "@shared/(.*)": "<rootDir>/src/shared/$1",
}
  • The <rootDir> if defined automatically, and points to the package.json directory
  • "@modules/(.*)" is a Regex for "any string starting with '@module/' followed by anything after it
  • "<rootDir>/src/modules/$1" is the corresponding directory. $1 is a pointer to the Regex expression between the parenthesis ((.*)). Other expressions will be pointed by $2, $3 and so on

After doing this, I was able to execute my tests without any problem.

Console output before follow the above steps:

$ jest
 FAIL  src/modules/appointments/services/CreateAppointmentService.spec.ts
  ● Test suite failed to run

    Cannot find module '...'

Console output after:

$ jest
 PASS  src/modules/appointments/services/CreateAppointmentService.spec.ts

Hope this help someone, Thanks!

于 2020-08-09T17:51:22.413 回答
0

现在我们使用一种解决方法:我们在 mono-repo 的多个 tsconfig.json 文件中定义了路径。我们将所有路径移至 root-tsconfig,现在测试再次运行。
但我们并不真正理解为什么会这样。

一个缺点是现在很容易意外引用您不应该在 lib 中使用的路径(因为 IDE 现在总是使用所有路径进行代码辅助)

于 2020-05-12T08:19:07.750 回答