简体   繁体   English

未找到 Jest 测试模块

[英]Jest testing module not found

I'm testing my js app with jest .我正在用jest测试我的 js 应用程序。 In my package.json I map all the modules like described in the documentation :在我的 package.json I map 所有模块中,如文档中所述:

 "jest": {
    "moduleNameMapper": {
      "@db/(.*)": "<rootDir>/db/$1",
      "@src/(.*)": "<rootDir>/src/$1",
      "@dto/(.*)": "<rootDir>/src/dto/$1",
      "@repos/(.*)": "<rootDir>/src/repos/$1",
      "@fetchers/(.*)": "<rootDir>/src/fetchers/$1",
      "@controllers/(.*)": "<rootDir>/src/controllers/$1",
      "@parsers/(.*)": "<rootDir>/src/parsers/$1",
      "@streams/(.*)": "<rootDir>/src/streams/$1",
      "@validators/(.*)": "<rootDir>/src/validators/$1"
    }
  },

However when I instantiate a new RestRepo that contains an import at the top, I get this error when I execute the test:但是,当我实例化一个包含顶部导入的新 RestRepo 时,执行测试时出现此错误:

Cannot find module '@db' from 'RestRepo.js'

Require stack:
  src/repos/RestRepo.js
  tests/unit/RestEndpoint.test.js

> 1 | const { RestEndpoint } = require('@db');
    |                          ^
  2 | 
  3 | class RestRepo {

How can I fix this and why is this happening?我该如何解决这个问题,为什么会这样?

You can try replacing您可以尝试更换

"@db/(.*)": "<rootDir>/db/$1",

with

"@db(.*)": "<rootDir>/db$1",

this way the capturing group will match an optional slash / if present and这样,捕获组将匹配可选的斜杠/如果存在,并且

require("@db")

will be interpreted as将被解释为

require("<rootDir>/db");

Or just add another entry或者只是添加另一个条目

"@db": "<rootDir>/db",

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM