test: add mock db test

This commit is contained in:
Innei
2022-01-14 15:36:17 +08:00
parent f4e0f713d2
commit 12a2da7d3c
11 changed files with 280 additions and 45 deletions

View File

@@ -0,0 +1,45 @@
import { MongoMemoryServer } from 'mongodb-memory-server'
import mongoose from 'mongoose'
let mongod: MongoMemoryServer
/**
* Connect to mock memory db.
*/
const connect = async () => {
mongod = await MongoMemoryServer.create()
const uri = mongod.getUri()
await mongoose.connect(uri, {
autoIndex: true,
maxPoolSize: 10,
})
}
/**
* Close db connection
*/
const closeDatabase = async () => {
await mongoose.connection.dropDatabase()
await mongoose.connection.close()
await mongod.stop()
}
/**
* Delete db collections
*/
const clearDatabase = async () => {
const collections = mongoose.connection.collections
for (const key in collections) {
const collection = collections[key]
await collection.deleteMany({})
}
}
export const dbHelper = {
connect,
close: closeDatabase,
clear: clearDatabase,
}