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

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 the UserModule's forFeature setup from the test database connection.
  • Fetching the repository via module.get('UserRepository') is unreliable; Nest/TypeORM recommends using typed repository tokens.
  • Your entities path ./**/*.entity.ts may fail in Jest, which runs compiled .js files instead of raw TypeScript.

Fix

  1. Reuse the AppModule's database configuration instead of adding a duplicate TypeOrmModule.forRoot()
  2. Use getRepositoryToken(User) to safely retrieve the User repository
  3. 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 configuration function in ConfigModule to use a separate database (e.g., gift_draw_test) when NODE_ENV=test to avoid polluting your dev data.
  • Replace manual data deletion: Use database transactions or savepoints to roll back changes after each test instead of raw DELETE queries. This is faster and safer.
  • Verify Jest path mapping: Ensure your jest-e2e.json has proper moduleNameMapper settings to resolve your src paths correctly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:32:50