Why testing also the DB part?

When developing an application for the long-term it’s absolutely mandatory to cover as much as possible — and reasonable — with tests to make sure any modifications to the code don’t change the desired behavior or introduce critical bugs.

With most backend applications the database is one of the most crucial parts so skipping or mocking all logic of it is just a bomb waiting to be triggered. Just imagine your servers are getting 100s of requests per second and suddenly ALL of them fail or introduce side-effects because you haven’t properly tested the code which interacts with the database… 💣💥🤯

Also, the interaction with the database and its defined logic is part of your application so it should also deserve to be handled and tested like the rest of it 😉

Why In-Memory DB? Can’t we simply use a “normal” one?

Now that we agreed that we also need to automate the testing of the interaction with our database — if not please stop here and read the last paragraph again — let’s get to the HOW.

If we would approach this very bluntly we would download MongoDB as binary and install it or run a MongoDB Docker image so have a local instance of our MongoDB running we can interact with. And even though it’s definitely recommended ( I would prefer the Docker one in this case ) for MANUAL testing on your local machine it’s not a good way for automated testing.

There are a couple of issues with this approach:

  • It definitely won’t work for CI/CD pipelines, at least not without A LOT of overhead in time and resources, like spinning up a clean docker container for each test case. Costing a lot of resources and introduces a lot of additional complexity.
  • When running the tests locally, you would always have to clean your local DB completely to create a clean state for your tests leading to loose of data you might currently using for your manual testing.
  • It’s not very performant to always write to a real existing DB and cleaning it completely after each test case. In-memory is simply faster

So it should be pretty clear that the in-memory approach should by far be the preferred one.

#javascript #mongodb #nodejs

Testing your Node.js Application with an In-Memory MongoDB
5.05 GEEK