• Stars
    star
    2,464
  • Rank 17,970 (Top 0.4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated 28 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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).

MongoDB In-Memory Server

Node.js CI NPM version Downloads stat Commitizen friendly TypeScript compatible codecov.io Backers on Open Collective Sponsors on Open Collective mongodb-memory-server-core

This package spins up an actual/real MongoDB server programmatically from within nodejs, for testing or mocking during development. By default it holds the data in memory. A fresh spun up mongod process takes about 7Mb of memory. The server will allow you to connect your favorite ODM or client library to the MongoDB server and run integration tests isolated from each other.

On install, this package downloads the latest MongoDB binaries and saves them to a cache folder. (only mongodb-memory-server-core does not download on postinstall)

On starting a new instance of the memory server, if the binary cannot be found, it will be auto-downloaded (if RUNTIME_DOWNLOAD option is truthy), thus the first run may take some time. All further runs will be fast, because they will use the downloaded binaries.

This package automatically downloads binaries from https://fastdl.mongodb.org/ according to your operating system. You can see all available versions for Linux (Ubuntu, RHEL, Debian, SUSE, Amazon), OSX, and Windows.

If your network is behind a proxy, make sure that it is configured through the HTTPS_PROXY or HTTP_PROXY environment variable.

Every MongoMemoryServer instance creates and starts a fresh MongoDB server on some free port. You may start up several mongod simultaneously. When you terminate your script or call stop(), the MongoDB server(s) will be automatically shutdown.

Works perfectly with any CI runner that can run NodeJS applications.

Table of Contents generated with DocToc

Installation

This tool provides three packages for different purposes:

  • With auto-download mongod binary on npm install (mongodb-memory-server, mongodb-memory-server-global-*)
  • Without auto-download on npm install (mongodb-memory-server-core)

Choose any package, because they are the same. They differ only in the default configuration, which you may override (see section Available options).

Requirements

  • NodeJS: 12.22+
  • Typescript: 4.4+ (if used)

And one of those (on Linux):

  • having lsb-core installed (or any that provides the lsb_release command)
  • having an /etc/os-release file that is compliant to the OS-Release Spec
  • having an /etc/*-release file that is compliant to the OS-Release Spec (and does not include lsb)
  • manually specify which version & system should be used

On Linux, you will also need libcurl4 (or libcurl3 on some older distro versions). This will probably only be an issue on "slim" Docker images.

Choose the Correct Package

Choose the right package for the task

Configuring which mongod binary to use

The default behavior is that version 5.0.13 for your OS will be downloaded. By setting Environment variables you are able to specify which version and binary will be downloaded:

export MONGOMS_DOWNLOAD_URL=https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1804-4.2.8.tgz
export MONGOMS_VERSION=4.2.8

Usage

Simple server start

A Normal Server can be easily started with:

import { MongoMemoryServer } from 'mongodb-memory-server';

// This will create an new instance of "MongoMemoryServer" and automatically start it
const mongod = await MongoMemoryServer.create();

const uri = mongod.getUri();

// The Server can be stopped again with
await mongod.stop();

Available options for MongoMemoryServer

All options are optional.

const mongod = new MongoMemoryServer({
  instance: {
    port?: number, // by default choose any free port
    ip?: string, // by default '127.0.0.1', for binding to all IP addresses set it to `::,0.0.0.0`,
    dbName?: string, // by default '' (empty string)
    dbPath?: string, // by default create in temp directory
    storageEngine?: string, // by default `ephemeralForTest`, available engines: [ 'ephemeralForTest', 'wiredTiger' ]
    replSet?: string, // by default no replica set, replica set name
    auth?: boolean, // by default `mongod` is started with '--noauth', start `mongod` with '--auth'
    args?: string[], // by default no additional arguments, any additional command line arguments for `mongod` `mongod` (ex. ['--notablescan'])
  },
  binary: {
    version?: string, // by default '5.0.13'
    downloadDir?: string, // by default node_modules/.cache/mongodb-memory-server/mongodb-binaries
    platform?: string, // by default os.platform()
    arch?: string, // by default os.arch()
    checkMD5?: boolean, // by default false OR process.env.MONGOMS_MD5_CHECK
    systemBinary?: string, // by default undefined or process.env.MONGOMS_SYSTEM_BINARY
  },
});

Replica Set start

A ReplicaSet can be easily started with:

import { MongoMemoryReplSet } from 'mongodb-memory-server';

// This will create an new instance of "MongoMemoryReplSet" and automatically start all Servers
const replset = await MongoMemoryReplSet.create({ replSet: { count: 4 } }); // This will create an ReplSet with 4 members

const uri = replset.getUri();

// The ReplSet can be stopped again with
await replset.stop();

Available options for MongoMemoryReplSet

All options are optional.

const replSet = new MongoMemoryReplSet({
  binary: binaryOpts, // same as for MongoMemoryServer
  instanceOpts: [
    {
      args, // any additional instance specific args
      port, // port number for the instance
      dbPath, // path to database files for this instance
      storageEngine, // same storage engine options
    },
    // each entry will result in a MongoMemoryServer (replSet.count will not count towards here)
  ],
  // unless otherwise noted below these values will be in common with all instances spawned:
  replSet: {
    name, // replica set name (default: 'testset')
    auth, //  enable auth support? (default: false)
    args, // any args specified here will be combined with any per instance args from `instanceOpts`
    count, // number of additional `mongod` processes to start (will not start any extra if instanceOpts.length > replSet.count); (default: 1)
    dbName, // default database for db URI strings. (default: uuid.v4())
    ip, // by default '127.0.0.1', for binding to all IP addresses set it to `::,0.0.0.0`
    oplogSize, // size (in MB) for the oplog; (default: 1)
    spawn, // spawn options when creating the child processes
    storageEngine, // default storage engine for instance. (Can be overridden per instance)
    configSettings: {
      // Optional settings for replSetInitiate command. See https://docs.mongodb.com/manual/reference/command/replSetInitiate/
      chainingAllowed: boolean, // When true it allows secondary members to replicate from other secondary members. When false, secondaries can replicate only from the primary.
      heartbeatTimeoutSecs: number, // Number of seconds that the replica set members wait for a successful heartbeat from each other. If a member does not respond in time, other members mark the delinquent member as inaccessible.
      heartbeatIntervalMillis: number, // The frequency in milliseconds of the heartbeats.
      electionTimeoutMillis: number, // The time limit in milliseconds for detecting when a replica set’s primary is unreachable.
      catchUpTimeoutMillis: number, // Time limit for a newly elected primary to sync (catch up) with the other replica set members that may have more recent writes.
    },
  },
});

Config Options

Documentation of Config Options

Simple test with MongoClient in Jest

A example test file for a single MongoMemoryServer within jest.

A example test file for multiple MongoMemoryServer within jest.

A example test file for a single MongoMemoryReplSet within jest.

Provide connection string to mongoose

// assuming [email protected]
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

const mongoServer = await MongoMemoryServer.create();

(async () => {
  await mongoose.connect(mongoServer.getUri(), { dbName: "verifyMASTER" });

  // your code here
  
  await mongoose.disconnect();
})();

For additional information it is recommended to read this article Testing a GraphQL Server using Jest with Mongoose

Test Runner Examples

Documentation for Test Runner Integration Examples

Docker Alpine

There isn't currently an official MongoDB release for alpine linux. This means that we can't pull binaries for Alpine (or any other platform that isn't officially supported by MongoDB), but you can use a Docker image that already has mongod built in and then set the MONGOMS_SYSTEM_BINARY variable to point at that binary. This should allow you to use mongodb-memory-server on any system on which you can install mongod manually.

Enable Debug Mode

The Debug mode can be enabled with an Environment-Variable or in the package.json "config" section:

MONGOMS_DEBUG=1 # also available case-insensitive values: "on" "yes" "true"

or

{
  "config": {
    "mongodbMemoryServer": {
      "debug": "1", // also available case-insensitive values: "on" "yes" "true"
    }
  }
}

Also see the Enable Debug Mode Guide.

Contributing

Contributing Guidelines are setup in CONTRIBUTING

Join Our Discord Server

To ask questions or just talk with us, join our Discord Server.

Documentation

Credits

Inspired by

Inspired by alternative runners for mongodb-prebuilt:

Maintainers

Funding

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

MIT

More Repositories

1

conf-talks

GraphQL на русском — здесь много статей и видео об этой замечательной технологии.
JavaScript
673
star
2

lvovich

Склонение названий городов, определения пола по ФИО, склонения имен по падежам
TypeScript
662
star
3

relay-northwind-app

A complex React, Relay, GraphQL demo app. Online demo:
JavaScript
105
star
4

graphql-rules-ru

67
star
5

webpack-plugin-graphql-schema-hot

🔥 Webpack plugin which tracks changes in your schema and generates its introspection in `json` and `txt` formats
JavaScript
66
star
6

mongoose-plugin-autoinc

Mongoose plugin that auto-increments any ID field on your schema every time a document is saved
JavaScript
63
star
7

wrike-graphql

Wrap REST API with GraphQL
TypeScript
37
star
8

example-apollo3

TypeScript
34
star
9

babel-plugin-transform-relay-hot

🔥 BabelRelayPlugin with hot reload
JavaScript
28
star
10

example-apollo2

TypeScript
25
star
11

module-federation-demo

JavaScript
20
star
12

graphql-typescript-boilerplate

TypeScript
14
star
13

mjml-with-images-loader

Converts MJML files with images to HTML and exports them as string or as Nodemailer config.
JavaScript
14
star
14

example-fragments-relay

TypeScript
11
star
15

migrating-from-mongoid-4-to-5

Non-official instruction for migration to Mongoid 5.0.0
5
star
16

graphql-workshop-ru

5
star
17

create-problem

yarn create problem
JavaScript
4
star
18

graphql-workshop-ua

GraphQL Workshop Kyiv (2019-05-11)
JavaScript
3
star
19

php-yandex-search

PHP
3
star
20

graphql-workshop-by

JavaScript
3
star
21

graphql-workshop-client-2020-02

ApolloClient 3, NextJS, SSR, TypeScript, GraphQL Subscriptions, graphql-code-generator
JavaScript
2
star
22

apollo-federation-test

JavaScript
2
star
23

nodkz.github.io

HTML
1
star
24

jest_mocha_mongoose

Jest can not test mongoose
JavaScript
1
star
25

gatsby-remark-use-frontmatter-path

If markdown file has a relative url to another markdown file then url will be replaced by frontmatter path value.
TypeScript
1
star
26

graphql-workshop-2019-11

TypeScript
1
star
27

peek-moped

Take a peek into the Moped (Mongoid) commands made within your Rails application.
Ruby
1
star
28

lingui-express-middleware

TypeScript
1
star
29

kkb-epay

JavaScript
1
star
30

sandbox-typegoose

TypeScript
1
star
31

boilerplate

Node GraphQL API Boilerplate
JavaScript
1
star