d512
d512

Reputation: 34083

Cleaning up mongodb after integration tests in node

I have an api written in node with a mongodb back end.

I'm using supertest to automate testing of an api. Of course this results in a lot of changes to database and I like to get some input on options for managing this. The goal is for each test to have no permanent impact on the database. The database should look exactly the same after the test is finished as it did before the test ran.

In my case, I don't want the database to be dropped or fully emptied out between tests. I need some real data maintained in the database at all times. I just want the changes by the tests themselves to be reverted.

With a relational database, I would put a transaction around each unit tests and roll it back after the test was done (pass or fail). As far as I know, this is not an option with mongo.

Some options I have considered:

Fake databases

I've heard of in-memory databases like fongo (which is a Java thing) and tingodb. I haven't used these but the issue with this type of solution is always that it requires a good parity with the actual product to maintain itself as a viable option. As soon as I used a mongo feature that the fake doesn't support I'll have a problem unit testing.

Manual cleanup

There is always the option of just having a routine that finds all the data added by the test (marked in some way) and removes it. You'd have to be careful about updates and deletes here. Also there is likely a lot of upkeep making sure the cleanup routine accurately cleans things up.

Database copying

If it were fast enough, maybe having a baseline test database and making a copy of it before each test could work. It'd have to be pretty fast though.

So how do people generally handle this?

Upvotes: 3

Views: 1169

Answers (1)

profesor79
profesor79

Reputation: 9473

I think this is a brand new way in testing without transaction.

imho - using mongo >=3.2, we can setup inMemory storage engine, which is perfect for this kind of scenario.

  1. Start mongo with inMemory
  2. restore database
  3. create a working copy for test
  4. perform a test on working copy
  5. drop working copy
  6. if more tests GOTO 3

Upvotes: 1

Related Questions