【发布时间】:2020-09-06 03:04:49
【问题描述】:
我正在尝试为 mongodb-memory-server 的 POC 编写示例应用程序,但不幸的是它无法正常工作。我检查了几个链接和博客,但似乎适用于所有人的代码对我不起作用。即使将超时时间增加到 1 分钟,Jest 测试也会超时。 getConnectionString 或 getUrl 都超时。我怀疑这个 mongodb-memory-server 永远不会启动。
以下是用于测试的 DB Handler
我使用的是 Windows 10
const mongoose = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server');
const mongoUnit = require('mongo-unit');
const mongod = new MongoMemoryServer();
jest.setTimeout(60000);
module.exports.connect = function(callback) {
mongod.getUri().then((mongoUri) => {
const mongooseOpts = {
autoReconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
};
mongoose.connect(mongoUri, mongooseOpts);
mongoose.connection.on('error', (e) => {
if (e.message.code === 'ETIMEDOUT') {
console.log(e);
mongoose.connect(mongoUri, mongooseOpts);
}
console.log(e);
});
mongoose.connection.once('open', () => {
console.log(`MongoDB successfully connected to ${mongoUri}`);
callback();
});
});
}
module.exports.closeDatabase = async () => {
await mongoose.connection.dropDatabase();
await mongoose.connection.close();
await mongod.stop();
}
module.exports.clearDatabase = async () => {
const collections = mongoose.connection.collections;
for (const key in collections) {
const collection = collections[key];
await collection.deleteMany();
}
}
【问题讨论】: