Step 7

We don't want to interact with the production database when testing our endpoints. There are many reasons for that, from the risk of corrupting the data to impending app function (at production) and other functional or security concerns. So instead, we want to create a dedicated test database or mock the database. The Jest testing library facilitates both of these options. Here, we will mock the database.

First, install Jest's preset for MongoDB:

npm install @shelf/jest-mongodb --save-dev

Next, add the configuration file jest.config.js to the root of the repository with the following content:

module.exports = {
  preset: "@shelf/jest-mongodb",
};

Jest's MongoDB preset can be configures to run a MongoDB Memory Server. Add the configuration file jest-mongodb-config.js to the root of the repository with the following content:

module.exports = {
  mongodbMemoryServerOptions: {
    instance: {
      dbName: "jest",
    },
    binary: {
      version: "4.0.2",
      skipMD5: true,
    },
    autoStart: false,
  },
};

We use the MongoDB Memory Server to run MongoDB "in memory." This package spins up an actual/real MongoDB server programmatically from NodeJS for testing or mocking during the development. During testing, instead of connecting our API to MongoDB in the cloud, we will connect it to MongoDB in the memory.