db.close()promise挂起:Jest在测试运行完成后一秒钟没有退出



尝试学习笑话,使用以下代码,测试不会终止。db.close promise的状态仍处于挂起状态。

当我执行测试时,我收到以下消息。你能帮我解决这个问题吗?谢谢

Jest在测试运行完成后一秒钟没有退出。

这通常意味着在测试中有一些异步操作没有停止。请考虑使用--detectOpenHandles运行Jest来解决此问题。

test('Should be ', async () => {
/*DO NOT call the next four function directly,  check if a  merchant/terminal exists before starting
a transaction and insert document if required.*/
//functions.insertTerminalRecordInMongo();
//functions.insertTerminalRecordInMongo();
var record = await functions.getMongoField('terminal', {'attributes.TID': 'T55001001'});
//functions.deleteTerminalRecordInMongo('terminal',{'attributes.TID' :'T55001001'})
DE22Test.buildTransactionAndSend({MTI: "1104", dataElements: {DE22: "XYZ"}})
expect(functions.getAsRequestField('DE22')).toBe("XYZ")
expect(functions.getAsResponseField('DE39')).toBe("00")
expect(functions.getAsResponseField('DE01')).toBe("00")
})

函数从mongodb中检索文档。

//Return a mongo record based on collectionName and FieldName
getMongoField: (collectionName, queryElement) => {
console.info("Querying Mongo");
mongoClient.connect(uri, function (err, db) {
if (err) throw err;
dbo = db.db("axis")
dbo.collection(collectionName).find({}, queryElement).toArray(function (err, result) {
if (err) throw err;
console.info('Queried document', result[0]);
});
db.close()
})
},

很抱歉我想发表评论,但由于声誉不佳,我不能。从代码片段中可以看出,数据库操作本质上是异步的,这意味着您需要实现异步代码,因此最后代码将在数据库关闭后终止。

const db = await mongoClient.connect(uri)
// Do your tasks
await db.close()

编辑

不要忘记将代码包装在try-catch块上以进行错误处理。

最新更新