You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS TypeScript项目Jest无法识别test目录测试文件问题

解决NestJS项目中Jest无法识别测试文件的问题

你的问题核心是Jest配置里的testRegex写法错误,导致无法匹配到测试文件,结合报错信息,按以下步骤修正:

  • 修正testRegex正则表达式
    你当前配置的"testRegex": "*.spec.ts"是shell通配符格式,不是Jest要求的正则表达式,Jest无法正确解析。改成以下正则,才能匹配所有以.spec.ts结尾的测试文件:

    "testRegex": ".*\\.spec\\.ts$"
    
  • 确认运行环境与rootDir匹配
    你的rootDir设为./test是正确的,但要确保运行Jest时的工作目录是项目根目录。如果用npm脚本,在package.json里配置的测试命令应该类似:

    "scripts": {
      "test:e2e": "jest --config ./jest-e2e.json"
    }
    

    这样执行npm run test:e2e时,Jest会从根目录加载配置,rootDir的相对路径就能正确指向测试文件夹。

  • 修正后的完整配置
    调整后的jest-e2e.json如下:

    {
      "moduleFileExtensions": [
        "js",
        "json",
        "ts"
      ],
      "rootDir": "./test",
      "testEnvironment": "node",
      "testRegex": ".*\\.spec\\.ts$",
      "transform": {
        "^.+\\.(t|j)s$": "ts-jest"
      },
      "moduleNameMapper": {
        "@helper/helper/(.*)": "<rootDir>/../libs/helper/src/$1",
        "@helper/helper": "<rootDir>/../libs/helper/src",
        "@appTests/appTests": "<rootDir>/../test"
      }
    }
    

做完以上调整后,重新运行测试命令,Jest应该能正确识别test目录下的所有.spec.ts文件并执行测试。

内容的提问来源于stack exchange,提问作者Mayur Kale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:02:36