@shelf/jest-mongodb

repository·master·Indexed 20 days ago

https://github.com/shelfio/jest-mongodb

A Jest preset that runs a MongoDB memory server for testing, allowing integration tests against a real, isolated MongoDB instance. It provides a custom TestEnvironment (MongoEnvironment) to automate the lifecycle of the server and injects connection details via global variables like __MONGO_URI__ and __MONGO_DB_NAME__. Supports shared or separate databases for Jest workers and replica set configurations via jest-mongodb-config.js.

Tokens
2.3K
Snippets
12
Records
16
Agent score
70%

What's inside @shelf/jest-mongodb

  1. Configure Jest with @shelf/jest-mongodb preset

    master

    Create a jest.config.js file and set the preset property to @shelf/jest-mongodb.

    Important: If you are using a custom jest.config.js, ensure you remove the testEnvironment property, as it will conflict with the preset.

    module.exports = {
      preset: '@shelf/jest-mongodb',
    };
  2. How the MongoEnvironment manages the MongoDB lifecycle

    master

    The MongoEnvironment class (exported as module.exports) is a custom Jest TestEnvironment that automates the lifecycle of a MongoDB instance for your tests.

    Lifecycle Stages:

    1. Initialization: During construction, it reads configuration from globalConfig.json (located in the Jest root directory) to determine whether to start a MongoMemoryServer or a MongoMemoryReplSet.
    2. Setup: When tests run, the environment starts the MongoDB instance (if a mongoUri is not already provided in the global config) and injects two key global variables into the test context:
      • global.__MONGO_URI__: The connection string for the running MongoDB instance.
      • global.__MONGO_DB_NAME__: The name of the database to use (defaults to a random UUID if not specified in globalConfig.json).
    3. Teardown: When tests finish, the environment automatically stops the MongoDB instance to clean up resources.
  3. Avoid infinite loops in Jest watch mode

    master

    The package creates a globalConfig.json file in the project root. When running Jest with the --watch flag, changes to this file can trigger an infinite loop. To prevent this, add globalConfig to your watchPathIgnorePatterns in jest.config.js.

    // jest.config.js
    module.exports = {
      watchPathIgnorePatterns: ['globalConfig'],
    };
  4. Use separate databases for each Jest worker

    master

    To ensure each Jest worker uses its own separate database, set useSharedDBForAllJestWorkers: false in jest-mongodb-config.js. Note that when using this option, the process.env variable is not created.

    module.exports = {
      mongodbMemoryServerOptions: {
        binary: {
          skipMD5: true,
        },
        autoStart: false,
        instance: {},
      },
    
      useSharedDBForAllJestWorkers: false,
    };
  5. Configure custom MongoDB URI environment variable name

    master

    By default, the library uses process.env.MONGO_URL. To use a different environment variable name, set the mongoURLEnvName field in jest-mongodb-config.js.

    module.exports = {
      mongodbMemoryServerOptions: {
        binary: {
          version: '4.0.3',
          skipMD5: true,
        },
        instance: {},
        autoStart: false,
      },
      mongoURLEnvName: 'MONGODB_URI',
    };
  6. Use a shared database for all Jest workers

    master

    To use the same database instance across all Jest workers, specify a dbName within the instance object in jest-mongodb-config.js.

    module.exports = {
      mongodbMemoryServerOptions: {
        binary: {
          version: '4.0.3',
          skipMD5: true,
        },
        instance: {
          dbName: 'jest',
        },
        autoStart: false,
      },
    };
  7. Configure MongoDB as a Replica Set

    master

    To run MongoDB as a replica set, add a replSet object to mongodbMemoryServerOptions and specify the count and storageEngine fields.

    module.exports = {
      mongodbMemoryServerOptions: {
        binary: {
          skipMD5: true,
        },
        autoStart: false,
        instance: {},
        replSet: {
          count: 3,
          storageEngine: 'wiredTiger',
        },
      },
    };
  8. Connect to MongoDB in tests using global.__MONGO_URI__

    master

    While the library sets process.env.MONGO_URL, it is preferable to use global.__MONGO_URI__ when connecting your MongoClient. This ensures compatibility when useSharedDBForAllJestWorkers: false is configured.

    const {MongoClient} = require('mongodb');
    
    describe('insert', () => {
      let connection;
      let db;
    
      beforeAll(async () => {
        connection = await MongoClient.connect(global.__MONGO_URI__, {});
        db = await connection.db();
      });
    
      afterAll(async () => {
        await connection.close();
      });
    });
  9. Configure jest-mongodb via the Config interface

    master

    The Config interface defines the options available for setting up the jest-mongodb environment. This configuration is typically used to control how the in-memory server is instantiated and how workers interact with the database.

    Available configuration keys:

    • mongodbMemoryServerOptions: Options passed directly to mongodb-memory-server (supports both MongoMemoryReplSetOpts and MongoMemoryServerOpts).
    • mongoURLEnvName: The name of the environment variable that will hold the MongoDB URI. Defaults to 'MONGO_URL'.
    • useSharedDBForAllJestWorkers: Determines if all Jest workers should share the same database instance. Defaults to true.
    export interface Config {
      mongodbMemoryServerOptions?: MongoMemoryReplSetOpts | MongoMemoryServerOpts;
      /**
       * @default 'MONGO_URL'
       */
      mongoURLEnvName?: string;
      /**
       * @default true
       */
      useSharedDBForAllJestWorkers?: boolean;
    }