我试图在每次e2e测试之前/之后将Nestjs / Typeorm与事务一起使用来启动和回滚数据库状态。
我在下面包括了一个代码片段尝试。我试图覆盖EntityManager提供程序,以便使用QueryRunner实例对其进行初始化,以便可以在每次测试之前/之后启动和回滚事务。但是,我似乎无法获取存储库(请参见下面的代码片段中的beforeEach方法中的注释)来使用我的重写的EntityManager实例,以启用成功的事务使用.....我认为这就是为什么事务在每次之后都不会回滚的原因测试已经完成?
let app: INestApplication;
let testModule: TestingModule;
afterEach(async () => {
const em: EntityManager = testModule.get(getEntityManagerToken('default'));
await em.queryRunner.rollbackTransaction();
});
beforeEach(async () => {
const con: Connection = testModule.get(Connection);
const em: EntityManager = testModule.get(getEntityManagerToken('default'));
const repo: CourseRepository = testModule.get(CourseRepository);
const result: boolean = repo.isEntityManagerMine(em); // false => the repo is not using the default entity manager
const conResult: boolean = repo.isConnectionMine(em.connection); // true => the repo is using the same connection
await em.queryRunner.startTransaction();
});
afterAll(async() => {
await app.close();
await testModule.close();
});
beforeAll(async () => {
testModule = await Test.createTestingModule({
imports: [AppModule],})
.overrideProvider(getEntityManagerToken('default'))
.useFactory({
factory: (connection: Connection): EntityManager => {
const queryRunner: QueryRunner = connection.createQueryRunner('master');
const entityManager: EntityManager = connection.createEntityManager(queryRunner);
return entityManager;
},
inject:[getConnectionToken('default')],
})
.compile();
app = testModule.createNestApplication();
await app.init();
});
// tests using request from supertest library