我正在为我的 api 编写 e2e 测试。为了实现e2e测试,我必须在创建TestingModule时在导入中使用AppModule:
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
})
...
问题是AppModule有导入
TypeOrmModule.forRootAsync({useFactory: getTypeOrmConfig, dataSourceFactory: getDataSource, })
,其中getTypeOrmConfig
从变量环境中获取配置。但在测试中,我正在嘲笑服务,并且不需要数据库连接。
我正在寻找一种用另一种配置覆盖此模块的方法,仅用于 e2e 测试。
更改 .env 中的变量不适合,因为集成测试正在使用实时数据库,并且我不想在我的 CI 中下载不同的
.env
来运行不同类型的测试。
我已经尝试过
overrideModule
:
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
})
.overrideModule(
TypeOrmModule.forRoot({}), || TypeOrmModule || TypeOrmModule.forRootAsync({})
)
.useModule(
TypeOrmModule.forRoot({
type: "sqlite",
database: "./test/database-mock/db",
}),
)
...
但它不起作用 - 应用程序仍然尝试连接到实时数据库。
有没有办法在创建 TestModule 时覆盖 AppModule 中导入的模块?我们可以覆盖 AppModule 内导入模块中的提供程序,我正在寻找执行此操作的方法,但使用导入模块。
在配置
TypeOrmModule
时,我故意使用 process.env
而不是 configService
来获取我的环境变量。
TypeOrmModule.forRootAsync({
useFactory: () => {
//N.B: I use process.env here instead of configService.get
// because of e2e tests. process.env can be mutated and updated
// with connection details for a testcontainer database
return {
type: 'postgres' as const,
host: process.env.DB_HOST,
port: +process.env.DB_PORT,
applicationName: 'app',
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
autoLoadEntities: true,
synchronize: IS_DEV,
logging: false,
};
},
});
这是因为我在 e2e 测试中使用
testcontainers
,并且我在测试的 beforeAll
钩子中改变了 process.env 对象。
postgreSqlContainer = await new PostgreSqlContainer()
.withName('testcontainer')
.withDatabase('testcontainer')
.start();
//update database enviroment variables in order for typeorm to connect enter code hereto the testcontainer DB
process.env.DB_HOST = postgreSqlContainer.getHost();
process.env.DB_PORT = postgreSqlContainer.getPort().toString();
process.env.DB_USERNAME = postgreSqlContainer.getUsername();
process.env.DB_PASSWORD = postgreSqlContainer.getPassword();
process.env.DB_NAME = postgreSqlContainer.getDatabase();
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
server = request(app.getHttpServer());
这允许我在测试运行之前在运行时更改数据库连接凭据。