Skip to main content
Version: 29.7

与 MongoDB 一起使用

借助 全局设置/拆卸异步测试环境 API,Jest 可以与 MongoDB 顺利工作。

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

使用 jest-mongodb 预设

¥Use jest-mongodb Preset

Jest MongoDB 提供了使用 MongoDB 运行测试所需的所有配置。

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

  1. 首先安装 @shelf/jest-mongodb

    ¥First install @shelf/jest-mongodb

npm install --save-dev @shelf/jest-mongodb
  1. 在 Jest 配置中指定预设:

    ¥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.

详细信息请参见 文档(配置 MongoDB 版本等)。

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