用途:为指定模块(模块名通过 $ARGUMENTS 传入)创建测试文件,适用于为控制器添加端到端测试,或为服务、仓储添加单元测试。
测试文件位置:控制器/服务测试放在 apps/core/test/src/modules/<module-name>/<module-name>.controller.spec.ts;仓储测试(使用真实 PostgreSQL)放在 apps/core/test/src/modules/<module-name>/<module-name>.repository.spec.ts。
三种测试模式:一是使用 @nestjs/testing 与 vitest 的单元测试,通过 vi.fn() 模拟依赖,适合控制器、服务或业务逻辑;二是使用 createE2EApp 的 E2E 测试,走完整 HTTP 管道(数据库为模拟),用 proxy.app.inject({ method, url, payload }) 发请求;三是使用 testcontainers 连接真实 PostgreSQL 的仓储测试,通过 PG_VERIFY_URL 环境变量启用,用 describeIfPg / describe.skip 模式避免在无数据库的 CI 中失败。
createE2EApp 行为:搭建 NestJS 测试模块,用 AuthTestingGuard 覆盖 AuthGuard(传 header 'test-token': 1 表示已认证),注册 ResponseInterceptor、JSONTransformInterceptor、DbQueryInterceptor、HttpCacheInterceptor 及全局 Zod 校验管道,创建基于 Fastify 的应用,返回 { app },并在 afterAll 自动关闭。
运行方式:设置 export PG_VERIFY_URL=postgres://mx:mx@127.0.0.1:5432/mx_verify,或用 docker run -d --name pg-test -e POSTGRES_USER=mx -e POSTGRES_PASSWORD=mx -e POSTGRES_DB=mx_verify -p 5433:5432 postgres:17-alpine 启动容器;单文件运行 pnpm test -- test/src/modules/<name>/<name>.repository.spec.ts,全部运行 pnpm test,监听模式 pnpm -C apps/core run test:watch。
限制与注意:createE2EApp 使用模拟 Redis 并绕过认证;响应经 JSONTransformInterceptor 转为 snake_case;分页响应含 data 与 pagination 字段;删除成功返回 204;仓储测试依赖 PG_VERIFY_URL,未设置时跳过。测试辅助文件位于 test/helper/ 与 test/mock/ 下。