How to use mongodb-memory-server - 10 common examples

To help you get started, we’ve selected a few mongodb-memory-server examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github entria / graphql-dataloader-boilerplate / test / environment / mongodb.js View on Github external
constructor(config) {
    // console.error('\n# MongoDB Environment Constructor #\n');
    super(config);
    this.mongod = new MongodbMemoryServer.default({
      instance: {
        // settings here
        // dbName is null, so it's random
        // dbName: MONGO_DB_NAME,
      },
      binary: {
        version: '4.0.0',
      },
      // debug: true,
      autoStart: false,
    });
  }
github keystonejs / keystone / packages / test-utils / lib / test-utils.js View on Github external
async function getMongoMemoryServerConfig() {
  mongoServer = mongoServer || new MongoDBMemoryServer();
  mongoServerReferences++;
  // Passing `true` here generates a new, random DB name for us
  const mongoUri = await mongoServer.getConnectionString(true);
  // In theory the dbName can contain query params so lets parse it then extract the db name
  const dbName = url
    .parse(mongoUri)
    .pathname.split('/')
    .pop();

  return { mongoUri, dbName };
}
github reactioncommerce / reaction / tests / TestApp.js View on Github external
async startMongo() {
    this.mongoServer = new MongoDBMemoryServer();
    const mongoUri = await this.mongoServer.getConnectionString();
    this.connection = await MongoClient.connect(mongoUri);
    this.db = this.connection.db(await this.mongoServer.getDbName());

    defineCollections(this.db, this.collections);

    const { Media } = setUpFileCollections({
      absoluteUrlPrefix: "http://fake.com",
      db: this.db,
      Logger: { info: console.info.bind(console) }, // eslint-disable-line no-console
      MediaRecords: this.collections.MediaRecords,
      mongodb
    });

    this.collections.Media = Media;
  }
github typegoose / typegoose / test / utils / mongooseConnect.ts View on Github external
import { MongoMemoryServer } from 'mongodb-memory-server';
import * as mongoose from 'mongoose';
import { isNullOrUndefined } from '../../src/internal/utils';
import { config } from './config';

/** its needed in global space, because we dont want to create a new instance everytime */
let instance: MongoMemoryServer = null;

if (config.Memory) {
  // only create an instance, if it is enabled in the config, wich defaults to "true"
  instance = new MongoMemoryServer();
}

/** is it the First time connecting in this test run? */
let isFirst = true;

interface ExtraConnectionConfig {
  dbName?: string;
  createNewConnection?: boolean;
}

// to not duplicate code
const staticOptions = {
  useNewUrlParser: true,
  useFindAndModify: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
github JKHeadley / rest-hapi / tests / e2e / end-to-end.tests.js View on Github external
const Logging = require('loggin')
const Q = require('q')
const Decache = require('decache')

// Import test groups
const BasicCrudTests = require('./basic-crud.tests')
const DocAuthTests = require('./doc-auth.tests')
const BasicEmbedTests = require('./basic-embed.tests')
const BasicNonEmbedTests = require('./basic-non-embed.tests')
const AuditLogTests = require('./audit-log.tests')
const AdvanceAssocTests = require('./advance-assoc.tests')
const DuplicateFieldTests = require('./duplicate-field.tests')
const MiscTests = require('./misc.tests')

const MongoMemoryServer = require('mongodb-memory-server').MongoMemoryServer
const mongoServer = new MongoMemoryServer({
  instance: {
    port: 27017,
    dbName: 'rest_hapi'
  }
})

// TODO: Possibly require this in every test and decache it to avoid unexpected
// errors between tests.
const Mongoose = require('mongoose')
Mongoose.Promise = Promise

let Log = Logging.getLogger('tests')
Log.logLevel = 'DEBUG'
Log = Log.bind('end-to-end')

const internals = {
github goemonjs / goemon / src / base / utilities / test-helper.ts View on Github external
export async function initializeDB() {
  mongoServer = new mongodbMemoryServer.MongoMemoryServer();
  const mongoUri = await mongoServer.getConnectionString();
  const mongooseOpts = { // options for mongoose 4.11.3 and above
    autoReconnect: true,
    reconnectTries: Number.MAX_VALUE,
    reconnectInterval: 1000,
  };

  await mongoose.connect(mongoUri, mongooseOpts, err => {
    if (err) {
      logger.error('Mongoose connect to MongoMemory failed!');
      logger.error(err);
    }
  });

  await Users.createUser({
    email: 'test@example.com',
github voluntarily / vly2 / server / util / test-memory-mongo.js View on Github external
constructor () {
    this.connection = null
    this.mms = new MongoMemoryServer({
      debug: false, // by default false
      binary: {
        debug: false
        // version: '4.0.5'
      }
    })
  }
github voteflux / THE-APP / packages / api / dev_mongo_server.ts View on Github external
console.log('started dev_mongo_server')

import MongodbMemoryServer from 'mongodb-memory-server';
// import { MongoClient } from 'mongodb'
import restore from 'mongodb-restore'

console.log('imported monogodb memory server && mongodb restore')

import DB from './flux/db'

let port = 53799

console.log("creating mongo memory server")
const mongod = new MongodbMemoryServer({instance: {port, dbName: "flux"}, debug: true});
console.log('created monogo memory server')

async function main() {
    const uri = await mongod.getConnectionString()
    console.log("DB URI:", uri)
    const db = await DB.init({}, uri)
    const {client, rawDb} = db.dbv1
    // always refresh for the moment
    if ((await rawDb.collections()).length < 5 || true) {
        // then we need to populate it
        console.log("loading saved db")
        await new Promise((res, rej) => restore({uri, drop: true, root: __dirname + "/dev-mongo-data/flux", callback: (e,v) => e ? rej(e) : res(v)}));
    }
    console.log("Mongo server ready!")
}
github TreeHacks / root / backend / setupMongo.js View on Github external
const MongodbMemoryServer = require('mongodb-memory-server');

const mongoServer = new MongodbMemoryServer.MongoMemoryServer({
  binary: { version: "latest" },
  instance: { port: 27017, dbName: "treehacks-application-portal-local" }
});

// mongoose.Promise = Promise;
console.warn("Setting up mongodb server...");
module.exports = async function () {
  await mongoServer.getConnectionString().then((uri) => {
    process.env.MONGODB_URI = uri;
    console.log("Mongodb server running on url", uri);

    // Set reference to mongod in order to close the server during teardown.
    global.__MONGOD__ = mongoServer;
  });
};
github graphql-compose / graphql-compose-mongoose / src / __mocks__ / mongooseCommon.js View on Github external
mongoose.connect = (async () => {
  const mongoServer = new MongodbMemoryServer();

  const mongoUri = await mongoServer.getConnectionString(true);

  // originalConnect.bind(mongoose)(mongoUri, { useMongoClient: true }); // mongoose 4
  originalConnect.bind(mongoose)(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true }); // mongoose 5

  mongoose.connection.on('error', e => {
    if (e.message.code === 'ETIMEDOUT') {
      console.error(e);
    } else {
      throw e;
    }
  });

  mongoose.connection.once('open', () => {
    // console.log(`MongoDB successfully connected to ${mongoUri}`);

mongodb-memory-server

MongoDB Server for testing (auto-download latest version). The server will allow you to connect your favourite ODM or client library to the MongoDB Server and run parallel integration tests isolated from each other.

MIT
Latest version published 1 month ago

Package Health Score

98 / 100
Full package analysis