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
  1. yarn add @shelf/jest-mongodb --dev
  1. Specify preset in your Jest configuration:
  1. {
  2. "preset": "@shelf/jest-mongodb"
  3. }
  1. Write your test
  1. const {MongoClient} = require('mongodb');
  2. describe('insert', () => {
  3. let connection;
  4. let db;
  5. beforeAll(async () => {
  6. connection = await MongoClient.connect(global.__MONGO_URI__, {
  7. useNewUrlParser: true,
  8. });
  9. db = await connection.db(global.__MONGO_DB_NAME__);
  10. });
  11. afterAll(async () => {
  12. await connection.close();
  13. await db.close();
  14. });
  15. it('should insert a doc into collection', async () => {
  16. const users = db.collection('users');
  17. const mockUser = {_id: 'some-user-id', name: 'John'};
  18. await users.insertOne(mockUser);
  19. const insertedUser = await users.findOne({_id: 'some-user-id'});
  20. expect(insertedUser).toEqual(mockUser);
  21. });
  22. });

There’s no need to load any dependencies.

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