Integration with Test Runners
This Guide will show how mongodb-memory-server
can be used with different frameworks
jest
jest version 29For usage with jest
it is recommended to use the globalSetup
and globalTeardown
options
config.ts
:
// this file could be anything (like a json directly imported)
export = {
Memory: true,
IP: '127.0.0.1',
Port: '27017',
Database: 'somedb'
}
jest.config.json
:
{
"preset": "ts-jest",
"globalSetup": "<rootDir>/test/globalSetup.ts",
"globalTeardown": "<rootDir>/test/globalTeardown.ts",
"setupFilesAfterEnv": [
"<rootDir>/test/setupFile.ts"
]
}
globalSetup.ts
:
import { MongoMemoryServer } from 'mongodb-memory-server';
import * as mongoose from 'mongoose';
import { config } from './utils/config';
export = async function globalSetup() {
if (config.Memory) { // Config to decide if an mongodb-memory-server instance should be used
// it's needed in global space, because we don't want to create a new instance every test-suite
const instance = await MongoMemoryServer.create();
const uri = instance.getUri();
(global as any).__MONGOINSTANCE = instance;
process.env.MONGO_URI = uri.slice(0, uri.lastIndexOf('/'));
} else {
process.env.MONGO_URI = `mongodb://${config.IP}:${config.Port}`;
}
// The following is to make sure the database is clean before a test suite starts
const conn = await mongoose.connect(`${process.env.MONGO_URI}/${config.Database}`);
await conn.connection.db.dropDatabase();
await mongoose.disconnect();
};
globalTeardown.ts
:
import { MongoMemoryServer } from 'mongodb-memory-server';
import { config } from './utils/config';
export = async function globalTeardown() {
if (config.Memory) { // Config to decide if an mongodb-memory-server instance should be used
const instance: MongoMemoryServer = (global as any).__MONGOINSTANCE;
await instance.stop();
}
};
and an setupFilesAfterEnv
can be used to connect something like mongoose
or mongodb
setupFile.ts
:
beforeAll(async () => {
// put your client connection code here, example with mongoose:
await mongoose.connect(process.env['MONGO_URI']);
});
afterAll(async () => {
// put your client disconnection code here, example with mongoose:
await mongoose.disconnect();
});
It is very important to limit the spawned number of Jest workers on machines that have many cores, because otherwise the tests may run slower than with fewer workers, because the database instance(s) may be hit very hard.
Use either --maxWorkers 4
or --runInBand
to limit the workers.
Keep in mind that jest's global-setup and global-teardown do not share a environment with the tests themself, and so require setupFile
/ setupFilesAfterEnv
to actually connect.
mocha / chai
mocha version (unknown)Start Mocha with --timeout 60000
cause first download of MongoDB binaries may take a time.
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
let mongoServer;
before(async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
await mongoose.connect(mongoUri);
});
after(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
describe('...', () => {
it('...', async () => {
const User = mongoose.model('User', new mongoose.Schema({ name: String }));
const cnt = await User.countDocuments();
expect(cnt).to.equal(0);
});
});
AVA test runner
For AVA there is a detailed written tutorial on how to test mongoose models with mongodb-memory-server by @zellwk.
Note that this tutorial is pre mongodb-memory-server 7.x.