Integration Testing: Mocking Your MongoDB Database in Node
I was in the process of writing my first test suite on a project. Unit tests for model validation were pretty straight forward, but when it came time to write integration tests, I had a difficult time testing my controllers since they were being called from my backend file (server.js). I’ll discuss what I did to get around this limitation below. The solution I came up with was to add a conditional statement in my server.js to choose the database based on the Node Environment.
In the example below is a simple CRUD-like app that will take a post request, validate it against our mongoose schema, and send a response back to the client. Our goal here for integration testing is to test our controller (literally called someController), which is serving as our Express middleware for the POST request to our specified route and our GET request to our api route.
To be continued…
- Testing frameworks: Mocha, supertest
- Assertion library: Chai