How to test mongoose models with jest and mockingoose

This page summarizes the projects mentioned and recommended in the original post on dev.to

Our great sponsors
  • SurveyJS - Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App
  • InfluxDB - Power Real-Time Data Analytics at Scale
  • WorkOS - The modern identity platform for B2B SaaS
  • mongodb-memory-server

    Spinning up mongod in memory for fast tests. If you run tests in parallel this lib helps to spin up dedicated mongodb servers for every test file in MacOS, *nix, Windows or CI environments (in most cases with zero-config).

  • The above test is clear and easy to understand, but the reality is that, while this can be applied to a lot of cases, things get very complicated when you have to start to mock things like dependencies, API calls, etc... And one very tricky case is when you have to test a function that invoke some models from an ODM like Mongoose, like doing some CRUD operations against a database. In some cases a solution could be to use an actual test database, so you don't mock anything but you use real data. The only problem with that is that is assuming that you must have a database at your disposal to run unit tests, and that's not always possible, plus you have to clean the database, and a pletora of other problems. Another solution could be to use a database that lives only in memory and only for the duration of your tests, like the excellent mongodb-memory-server package. But while this will work most of the times, if you deploy your code on any CI/CD you might encounter problems (and I did!). Also a key factor of unit testing, is that you shouldn't rely on external services run them, unlike E2E tests for example. What you should do is to mock most of the dependencies you need, as your goal is to just test the function and no deeper than that.

  • SurveyJS

    Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.

    SurveyJS logo
NOTE: The number of mentions on this list indicates mentions on common posts plus user suggested alternatives. Hence, a higher number means a more popular project.

Suggest a related project

Related posts