How to test server code that relies on a database?

I have a NodeJS/MongoDB app. There are lots of functions, and I have a bunch of unit tests to test specifically logic of some functions.

There is also code that uses Agenda (task scheduling library) which itself requires MongoDB for persistance.
How do I set up test environment, so that both, unit tests and Agenda/MongoDB code is tested?
Should I run all the tests in a Docker environment, or separate simple unit tests from Agenda/MongoDB tests?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I’d recommend writing unit tests that do not depend on a database. Mock out the data-access layer in your application. I should be able to npm run test and have it complete reasonably quickly with no external dependencies. This will not test every variation or every real-world scenario or problems with object mapping, but it will give you reasonable confidence that things are running correctly, and it is quick and easy to run.

Separately, you should also have integration tests that depend on a real-world setup. Imagine you have your application and its database deployed in containers, maybe in a local Compose setup. You should be able to make a request to your application, observe some external changes, make another request, and see the persisted data. The test itself has no particular dependency on Docker and can usually be launched from outside a container. The test should target the exact images you’re planning to deploy to production.

So in both of these cases, the tests themselves run outside of Docker; for unit tests, as part of your local pre-commit build-and-test sequence, and for the integration tests, as a client of the packaged application. You should not need to build a different image to run tests or to include test code or libraries in your image.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x