0.6.1 • Published 6 years ago
mockodb v0.6.1
MockoDB
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.