我正在编写一个e2e测试,应用程序的配置中有type或postgres 2数据库,测试成功,执行了与数据库的所有操作,但是当应用程序关闭时,标题中弹出错误。
database.module
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
name: 'adminpanel',
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('ADMINPANEL_DB_HOST'),
port: configService.get('ADMINPANEL_DB_PORT'),
username: configService.get('ADMINPANEL_DB_USERNAME'),
password: configService.get('ADMINPANEL_DB_PASSWORD'),
database: configService.get('ADMINPANEL_DB_NAME'),
entities: [__dirname + '/../modules/adminpanel/entities/*.entity.js'],
synchronize: true,
autoLoadEntities: true,
// logging: true,
}),
}),
2db...
],
providers: [],
exports: [TypeOrmModule],
})
export class DataBaseModule {}
e2e test
beforeAll:
dataSource = moduleFixture.get<DataSource>(
getDataSourceToken('adminpanel'),
);
afterAll:
if (dataSource.isInitialized) {
await dataSource.destroy();
}
try {
await app.close();
} catch (e) {
console.error(e);
}
dataSource.IsInitialized == true,这会导致理解要做什么的问题(
我尝试以不同的方式从database.module导出数据源,但这导致了更多问题并且与数据库的连接消失了,我还尝试使数据源成为AppModule和e2e测试本身的提供者
我找到了解决问题的方法。 我有database.module和typeorm初始化:
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
name: 'adminpanel',
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('ADMINPANEL_DB_HOST'),
port: configService.get('ADMINPANEL_DB_PORT'),
username: configService.get('ADMINPANEL_DB_USERNAME'),
password: configService.get('ADMINPANEL_DB_PASSWORD'),
database: configService.get('ADMINPANEL_DB_NAME'),
entities: [__dirname + '/../modules/adminpanel/entities/*.entity.js'],
synchronize: true,
autoLoadEntities: true,
// logging: true,
}),
}),
需要添加第二个名称:“adminpanel”; 但已经在 useFactory 内部了。
结果如下:
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
name: 'adminpanel',
useFactory: (configService: ConfigService) => ({
name: 'adminpanel',
type: 'postgres',
host: configService.get('ADMINPANEL_DB_HOST'),
port: configService.get('ADMINPANEL_DB_PORT'),
username: configService.get('ADMINPANEL_DB_USERNAME'),
password: configService.get('ADMINPANEL_DB_PASSWORD'),
database: configService.get('ADMINPANEL_DB_NAME'),
entities: [__dirname + '/../modules/adminpanel/entities/*.entity.js'],
synchronize: true,
autoLoadEntities: true,
// logging: true,
}),
}),
现在一切正常)