8

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!

2
  • I've just found an idea to stub getRepository() to use connection set up in a test with a started transaction. I am not familiar with stubs yet, will play with it now!
    – outluch
    Jan 17, 2019 at 16:29
  • Interesting, please let me know if it works @outluch :)
    – Ezequiel
    Jan 18, 2019 at 17:21

3 Answers 3

7

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.

1

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

1
  • nice! The more alternatives we have, the better for the community :D Jun 6, 2021 at 14:52
0

You might consider an alternative approach. Instead of isolating tests through transactions you could isolate them through serialization + multiple databases.

At a high level the approach is as follows:

  • Split tests into N groups where each group gets its own database and N is roughly the number of cpu cores you have.
  • Within each group tests are run serially. Tests also reset the database when they start.
  • Each group runs in parallel to each other.

This approach is remarkably easy to set up with Jest and Docker and allows you to achieve a high degree parallelism.

I wrote a blog post describing this approach in more detail here: https://blog.mikevosseller.com/2021/11/25/how-to-run-jest-with-multiple-test-databases.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.