Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tests with transactions in TypeORM

Tags:

typeorm

On Rails, each test case creates an ActiveRecord transaction, which allows to test everything and then revert the database to the original state, without having to drop all tables, or anything like that that might affect seeders, etc. Is it possible to do something like this on TypeORM? From what I've seen, the main issue with the way transactions are documented to work is that a call to another method would not be using the created transaction, but I'm hoping I'm missing some other way of implementing it.

Thanks!

like image 515
Ezequiel Avatar asked Jan 22 '18 15:01

Ezequiel


2 Answers

I had exactly the same expectations as you. Coming from Rails and Spring, I expected to have transactional tests and found no solution directly from Typeorm.

It is hard to reuse the same transactions during the tests because the connection class always create a new QueryRunner for every database command or transaction. Diving into TypeORM, the solution I found was to monkey patch the method which creates the query runner, to reuse it during the tests. I created this library to reuse this code in several projects: https://github.com/viniciusjssouza/typeorm-transactional-tests.

like image 60
viniciusjssouza Avatar answered Oct 06 '22 19:10

viniciusjssouza


I know this is quite late, but I also actually worked on a solution which you can see here: https://www.npmjs.com/package/typeorm-test-transactions

A disclaimer from my side is that you have to use the @Transactional() decorator, but I like how that makes the code a lot cleaner and you don't have to pass the transaction manager down.

@viniciusjssouza I checked your solution and I really like it! It's funny, I think we both had the same problem at the same time :P

like image 26
Kerren Avatar answered Oct 06 '22 19:10

Kerren