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

NestJS TypeScript执行npm test时出现Cannot find module错误求助

问题:执行npm test时无法找到模块'src/category/category.module'

执行npm test命令时出现模块找不到的错误,报错指向src/info/info.module.ts文件中导入CategoryModule的语句。尝试过论坛和文档中的多种排查方案,问题仍未解决,需要有效指导。

错误信息

FAIL  test/app.e2e-spec.ts
● Test suite failed to run

Cannot find module 'src/category/category.module' from '../src/info/info.module.ts'

Require stack:
D:/astagatra-web/server/src/info/info.module.ts
D:/astagatra-web/server/src/app.module.ts
app.e2e-spec.ts

1 | import { Module } from "@nestjs/common";
2 | import { DynamooseModule } from "nestjs-dynamoose";
> 3 | import { CategoryModule } from "src/category/category.module";
  | ^
4 | import { SharedServiceModule } from "src/shared/services/service.module";
5 | import { UserModule } from "src/user/user.module";
6 | import { InfoPublicController } from "./controller/info.public.controller";

at Resolver.resolveModule (../node_modules/jest-resolve/build/resolver.js:324:11)
at Object.<anonymous> (../src/info/info.module.ts:3:1)

相关配置文件

package.json

{
  "name": "nest-server",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "engines": {
    "npm": ">=7.0.0",
    "node": ">=14.0.0"
  },
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "NODE_ENV=prod node dist/main",
    "start:dev": "NODE_ENV=dev nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": " NODE_ENV=prod node dist/main",
    "start:prod-local": "ALLOW_ALL=true NODE_ENV=prod nest start",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json",
    "deploy": "npm run build && eb deploy"
  },
  "dependencies": {
    "@aws-sdk/client-cognito-identity-provider": "^3.53.0",
    "@aws-sdk/client-s3": "^3.53.1",
    "@aws-sdk/client-ses": "^3.56.0",
    "@aws-sdk/s3-request-presigner": "^3.53.1",
    "@kurkle/color": "^0.1.9",
    "@nestjs/common": "^8.0.0",
    "@nestjs/config": "^1.1.7",
    "@nestjs/core": "^8.0.0",
    "@nestjs/jwt": "^8.0.0",
    "@nestjs/mapped-types": "*",
    "@nestjs/passport": "^8.2.1",
    "@nestjs/platform-express": "^8.0.0",
    "@nestjs/schedule": "^1.0.2",
    "@nestjs/swagger": "^5.1.5",
    "@nestjs/throttler": "^2.0.0",
    "@nestjs/typeorm": "^8.0.2",
    "@types/bcrypt": "^5.0.0",
    "@types/cache-manager": "^3.4.3",
    "@types/cron": "^1.7.3",
    "@types/express-session": "^1.17.4",
    "@types/html-pdf": "^3.0.0",
    "@types/lodash": "^4.14.178",
    "@types/mime": "^2.0.3",
    "@types/multer": "^1.4.7",
    "@types/multer-s3": "^2.7.11",
    "@types/mustache": "^4.1.2",
    "@types/nodemailer": "^6.4.4",
    "@types/passport-local": "^1.0.34",
    "@types/sanitize-html": "^2.6.2",
    "amazon-cognito-identity-js": "^5.2.6",
    "aws-sdk": "^2.1087.0",
    "bcrypt": "^5.0.1",
    "cache-manager": "^3.6.0",
    "class-transformer": "^0.4.0",
    "class-validator": "^0.13.1",
    "dotenv": "^10.0.0",
    "dynamoose": "^2.8.5",
    "express-mysql-session": "^2.1.7",
    "express-session": "^1.17.2",
    "fs": "^0.0.1-security",
    "fuzzysort": "^1.2.1",
    "html-pdf": "^3.0.1",
    "jwks-rsa": "^2.0.5",
    "lodash": "^4.17.21",
    "mime": "^3.0.0",
    "moment": "^2.29.1",
    "multer": "^1.4.3",
    "multer-s3": "^2.10.0",
    "mustache": "^4.2.0",
    "nestjs-dynamoose": "^0.3.4",
    "node-fetch": "^3.2.0",
    "nodemailer": "^6.7.2",
    "passport": "^0.5.2",
    "passport-jwt": "^4.0.0",
    "passport-local": "^1.0.0",
    "path": "^0.12.7",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.2.0",
    "sanitize-html": "^2.7.0",
    "swagger-ui-express": "^4.1.6",
    "utils-decorators": "^2.0.0",
    "uuid": "^8.3.2"
  },
  "devDependencies": {
    "@nestjs/cli": "^8.0.0",
    "@nestjs/schematics": "^8.0.0",
    "@nestjs/testing": "^8.0.0",
    "@types/express": "^4.17.13",
    "@types/jest": "^27.0.1",
    "@types/node": "^16.11.9",
    "@types/supertest": "^2.0.11",
    "@typescript-eslint/eslint-plugin": "^5.0.0",
    "@typescript-eslint/parser": "^5.0.0",
    "eslint": "^8.0.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "jest": "^27.2.5",
    "prettier": "^2.3.2",
    "source-map-support": "^0.5.20",
    "supertest": "^6.1.3",
    "ts-jest": "^27.0.3",
    "ts-loader": "^9.2.3",
    "ts-node": "^10.0.0",
    "tsconfig-paths": "^3.10.1",
    "typescript": "^5.2.2"
  },
  "jest": {
    
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

tsconfig.json

"compilerOptions": {
  "module": "commonjs",
  "declaration": true,
  "removeComments": true,
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "allowSyntheticDefaultImports": true,
  "target": "es2017",
  "sourceMap": true,
  "outDir": "./dist",
  "baseUrl": "./",
  "incremental": true,
  "skipLibCheck": true,
  "strictNullChecks": false,
  "noImplicitAny": false,
  "strictBindCallApply": false,
  "forceConsistentCasingInFileNames": false,
  "noFallthroughCasesInSwitch": false
}

info.module.ts

import { Module } from "@nestjs/common";
import { DynamooseModule } from "nestjs-dynamoose";
import { CategoryModule } from "src/category/category.module";
import { SharedServiceModule } from "src/shared/services/service.module";
import { UserModule } from "src/user/user.module";
import { InfoPublicController } from "./controller/info.public.controller";
import { InfoController } from "./controller/info.tools.controller";
import { CommentSchema } from "./schema/comment.schema";
import { InfoSchema } from "./schema/info.schema";
import { LikesSchema } from "./schema/likes.schema";
import { CommentService } from "./service/comment.service";
import { InfoCache } from "./service/info.cache";
import { InfoService } from "./service/info.service";
import { LikeService } from "./service/likes.service";

@Module({
  imports: [
    SharedServiceModule,
    CategoryModule,
    UserModule,
    DynamooseModule.forFeature([
      {
        name: "info",
        schema: InfoSchema,
        options: { throughput: "ON_DEMAND" },
      },
      {
        name: "likes",
        schema: LikesSchema,
        options: { throughput: "ON_DEMAND" },
      },
      {
        name: "comment",
        schema: CommentSchema,
        options: { throughput: "ON_DEMAND" },
      },
    ]),
  ],
  controllers: [InfoController, InfoPublicController],
  providers: [InfoService, LikeService, CommentService, InfoCache],
  exports: [InfoCache],
})
export class InfoModule {}

解决方案

1. 配置Jest的模块路径映射

在package.json的jest配置中添加moduleNameMapper,让Jest识别以src/开头的导入路径,和tsconfig.json的baseUrl对应:

"jest": {
  // 保留现有配置
  "moduleNameMapper": {
    "^src/(.*)$": "<rootDir>/$1"
  }
}

2. 同步E2E测试的路径映射

如果执行的是E2E测试(错误指向test/app.e2e-spec.ts),检查test/jest-e2e.json文件,添加相同的路径映射:

{
  // 保留现有配置
  "moduleNameMapper": {
    "^src/(.*)$": "<rootDir>/../src/$1"
  }
}

3. 验证文件路径和大小写

  • 确认src/category/category.module.ts文件真实存在,路径拼写完全正确
  • Windows系统对路径大小写不敏感,但Jest解析时可能区分,确保导入语句的路径和实际文件路径大小写一致

4. 启用tsconfig-paths的Jest支持

修改scripts中的测试命令,加入tsconfig-paths/register,让Jest运行时解析tsconfig的路径配置:

"scripts": {
  // 保留其他脚本
  "test": "node -r tsconfig-paths/register node_modules/.bin/jest",
  "test:e2e": "node -r tsconfig-paths/register node_modules/.bin/jest --config ./test/jest-e2e.json"
}

5. 清理缓存后重新测试

执行以下命令清除编译产物和Jest缓存,再重新运行测试:

npm run prebuild
npx jest --clearCache
npm test

内容的提问来源于stack exchange,提问作者Shitta 25

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 21:30:52