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
  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @shelf/jest-mongodb
  1. yarn add --dev @shelf/jest-mongodb
  1. pnpm add --save-dev @shelf/jest-mongodb
  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(globalThis.__MONGO_URI__, {
  7. useNewUrlParser: true,
  8. useUnifiedTopology: true,
  9. });
  10. db = await connection.db(globalThis.__MONGO_DB_NAME__);
  11. });
  12. afterAll(async () => {
  13. await connection.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. });

无需加载任何依赖项。

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