Skip to main content
Version: 26.x

Using with MongoDB

With the Global Setup/Teardown and Async Test Environment APIs, Jest can work smoothly with MongoDB.

Use jest-mongodb Preset#

Jest MongoDB provides all required configuration to run your tests using MongoDB.

  1. First install @shelf/jest-mongodb
yarn add @shelf/jest-mongodb --dev
  1. Specify preset in your Jest configuration:
{
"preset": "@shelf/jest-mongodb"
}
  1. Write your test
const {MongoClient} = require('mongodb');
describe('insert', () => {
let connection;
let db;
beforeAll(async () => {
connection = await MongoClient.connect(global.__MONGO_URI__, {
useNewUrlParser: true,
});
db = await connection.db(global.__MONGO_DB_NAME__);
});
afterAll(async () => {
await connection.close();
await db.close();
});
it('should insert a doc into collection', async () => {
const users = db.collection('users');
const mockUser = {_id: 'some-user-id', name: 'John'};
await users.insertOne(mockUser);
const insertedUser = await users.findOne({_id: 'some-user-id'});
expect(insertedUser).toEqual(mockUser);
});
});

There's no need to load any dependencies.

See documentation for details (configuring MongoDB version, etc).

Last updated on by Sébastien Lorber