跳至主要內容
版本:29.7

與 MongoDB 搭配使用

透過 全域設定/中斷非同步測試環境 API,Jest 可以順利與 MongoDB 搭配使用。

使用 jest-mongodb 預設值

Jest MongoDB 提供所有必要的設定,讓您使用 MongoDB 執行測試。

  1. 首先安裝 @shelf/jest-mongodb
npm install --save-dev @shelf/jest-mongodb
  1. 在您的 Jest 設定中指定預設值
{
"preset": "@shelf/jest-mongodb"
}
  1. 撰寫您的測試
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);
});
});

無需載入任何依賴項。

請參閱 文件 以取得詳細資料(設定 MongoDB 版本等)。