Mongoose is a great tool, as it helps you build Node apps which use MongoDB more easily. Instead of having to sprinkle the model-related logic all over the place, it’s easy to define the functionality as Mongoose models. Querying MongoDB for data also becomes quick and easy – and if you ever need some custom querying logic, that can be hidden away into the model as well.
But how do you test all that logic? When trying to test them, Mongoose models can be a bit daunting at first. Ideally, we’d like to test them without having to connect to a database – after all, a connection would make the tests slow and difficult to set up, because we need to manage database state. But how can we do that?
In fact, Mongoose related questions are some of the most common library-specific ones I get from my readers.
So, let’s find out how we can test Mongoose models. We’ll go in depth with examples for the most common testing situations you’d encounter with Mongoose.