Skip to main content
Versão: 29.7

Using with MongoDB

Com Global Setup/Teardown e Async Test Environment APIs, Jest pode funcionar bem com MongoDB.

Use jest-mongodb Preset

O Jest MongoDB fornece todas as configurações necessárias para executar seus testes usando o MongoDB.

  1. Primeiro instale @shelf/jest-mongodb
npm install --save-dev @shelf/jest-mongodb
  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(globalThis.__MONGO_URI__, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
db = await connection.db(globalThis.__MONGO_DB_NAME__);
});

afterAll(async () => {
await connection.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.

Veja a documentação para detalhes (configurando a versão do MongoBD, etc).