【发布时间】:2019-09-10 15:04:20
【问题描述】:
我正在尝试使用带有事务的 Nestjs/Typeorm 在每次 e2e 测试之前/之后启动和回滚数据库状态。
我在下面包含了一个代码 sn-p 尝试。我正在尝试覆盖 EntityManager 提供程序,以便使用 QueryRunner 实例对其进行初始化,以便我可以在每次测试之前/之后启动和回滚事务。但是,我似乎无法获取存储库(请参阅下面代码 sn-p 中 beforeEach 方法中的 cmets)来使用我覆盖的 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
【问题讨论】:
-
但是你肯定想要测试运行之前的状态,所以擦除数据库不是一个选项?!
-
可能不得不走那条路......虽然为了性能更愿意回滚事务,但令人费解的是为什么存储库不使用来自提供者的 EntityManager 实例......
-
我使用
await getConnection().synchronize(true);删除数据库,这对于我的目的来说足够快。也许试试看,如果你没有明显的性能损失,那就足够了 -
谢谢@KimKern,可能要试一试...