I'm using TypeORM in active record mode and I wanted to apply transactions. In particular, I wanted each of my tests to be wrapped in a transaction, so, achieving something like this:
beforeEach(async () => {
// start transaction
})
afterEach(async () => {
// rollback transacttion
})
test("create new", async () => {
// create new
}
So, I tried this:
let queryRunner: any
beforeEach(async () => {
queryRunner = getConnection().createQueryRunner()
await queryRunner.connect()
await queryRunner.startTransaction()
})
afterEach(async () => {
await queryRunner.rollbackTransaction()
await queryRunner.release()
})
test("Create user", async () => {
let user = new User()
await user.save()
})
but it looks like those transactions are started on a separate context/connection, because after the test runs, I can see the record in the database.
How do I make the transaction affect the user being saved?
I think you have to connect your query runner to the db. Try to modify your code as follows:
Also, you should use try-catch-finally block.