NestJS+TypeORM启动E2E测试失败,遇两类错误求助
Let's tackle your two E2E testing issues with NestJS and TypeORM step by step:
1. TypeError: Cannot read property 'getHttpServer' of undefined
Root Cause
Your test module imports both AppModule (which already loads TypeORM config via ConfigModule) and a duplicate TypeOrmModule.forRoot() call. This creates conflicting database connections, which breaks the Nest application initialization process. The missing console.error output confirms that your beforeAll hook likely threw an uncaught error, leaving app as undefined.
Fix
Remove the redundant TypeOrmModule.forRoot() from your test module and reuse the existing database configuration from AppModule. If you need a dedicated test database, adjust your ConfigModule to handle the test environment separately.
Modified app.e2e-spec.ts:
import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import * as request from 'supertest'; import { AppModule } from '../src/app.module'; describe('AppController (e2e)', () => { let app: INestApplication; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], // Reuse existing config from AppModule }).compile(); app = moduleFixture.createNestApplication(); await app.init(); }); afterAll(async () => { await app.close(); }); it('/api/ (GET)', async () => { return request(app.getHttpServer()) .get('/api/') .expect(200) .expect('Working!'); }); });
2. No repository for "User" was found
Root Cause
- You're again duplicating
TypeOrmModule.forRoot()in the user test, which disconnects theUserModule'sforFeaturesetup from the test database connection. - Fetching the repository via
module.get('UserRepository')is unreliable; Nest/TypeORM recommends using typed repository tokens. - Your
entitiespath./**/*.entity.tsmay fail in Jest, which runs compiled.jsfiles instead of raw TypeScript.
Fix
- Reuse the
AppModule's database configuration instead of adding a duplicateTypeOrmModule.forRoot() - Use
getRepositoryToken(User)to safely retrieve the User repository - Update your TypeORM entity path to support both TS and JS files
Modified user.e2e-spec.ts:
import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import { Repository, getRepositoryToken } from 'typeorm'; import { UserModule } from '../src/user/user.module'; import { User } from '../src/user/entities/user.entity'; import { AppModule } from '../src/app.module'; describe('User', () => { let app: INestApplication; let repository: Repository<User>; beforeAll(async () => { const module = await Test.createTestingModule({ imports: [AppModule, UserModule], // Reuse AppModule's DB config }).compile(); app = module.createNestApplication(); // Safe way to fetch the User repository repository = module.get<Repository<User>>(getRepositoryToken(User)); await app.init(); }); afterEach(async () => { await repository.query(`DELETE FROM users;`); }); afterAll(async () => { await app.close(); }); // Example test case it('should count saved users correctly', async () => { await repository.save({ /* add your User entity fields here */ }); const userCount = await repository.count(); expect(userCount).toBe(1); }); });
Bonus Optimization Tips
- Use a dedicated test database: Update your
configurationfunction inConfigModuleto use a separate database (e.g.,gift_draw_test) whenNODE_ENV=testto avoid polluting your dev data. - Replace manual data deletion: Use database transactions or savepoints to roll back changes after each test instead of raw
DELETEqueries. This is faster and safer. - Verify Jest path mapping: Ensure your
jest-e2e.jsonhas propermoduleNameMappersettings to resolve yoursrcpaths correctly.
内容的提问来源于stack exchange,提问作者Xalion

