Skip to content
This repository has been archived by the owner on May 6, 2019. It is now read-only.

j-maas/mockodb

Repository files navigation

MockoDB

npm build status code style: prettier

In-memory mock for MongoDB in unit tests.

Inspired by mongo-unit.

Installation

MockoDB is available on NPM.

yarn add mockodb
npm install --save mockodb

Usage

import { MockoDb } from "mockodb";
import { MongoClient } from "mongodb";

async function demo() {
  const mockoDb = await MockoDb.boot();

  // You can now connect to the database.
  const client = await MongoClient.connect(mockoDb.url.href);
  ...

  // At any time you can drop all databases.
  await mockoDb.reset();
  ...

  // You need to take care of shutting down the db.
  await mockoDb.shutdown();
}

You can also control individual databases.

import { MockoDb } from "mockodb";
import { MongoClient } from "mongodb";

async function demo() {
  const mockoDb = await MockoDb.boot();
  // Open a new database with a random name.
  const dbHandle = await mockoDb.open();
  const client = await MongoClient.connect(dbHandle.url.href);
  ...

  // Reset only that database.
  await dbHandle.drop();

  await mockoDb.shutdown();
}

Preloading

Note that MockoDb.boot() might attempt to download the MongoDB binaries on the first run. You can preload those libraries explicitly before your tests run using the preload() function:

import { preload } from "mockodb";

describe("test suite", () => {
  beforeAll(async () => {
    jest.setTimeout(100_000); // Preload might take a while.
    await preload();
  });

  // ...
});

Alternatively, for a more direct use inside your CI's script, this package exposes the mockodb-preload command in its bin:

yarn install
mockodb-preload
yarn test

Download Directory

MockoDB will download the MongoDB binaries into its folder. Therefore you can simply cache your node_modules on your CI, making it download the MongoDB binaries once on the first run and whenever you clear your cache.

About

In-memory mock for MongoDB in unit tests.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published