Javascript db.close()promise挂起:测试运行完成后一秒钟Jest未退出
尝试学习jest,使用以下代码测试不会终止。db.close承诺的状态仍处于挂起状态 我在执行测试时收到以下消息。你能帮我解决这个问题吗?谢谢 测试运行完成后一秒钟,Jest未退出 这通常意味着有一些异步操作在测试中没有停止。考虑使用<代码>运行jest-DeTeCopeNotos<代码>来解决这个问题。Javascript db.close()promise挂起:测试运行完成后一秒钟Jest未退出,javascript,mongodb,jestjs,Javascript,Mongodb,Jestjs,尝试学习jest,使用以下代码测试不会终止。db.close承诺的状态仍处于挂起状态 我在执行测试时收到以下消息。你能帮我解决这个问题吗?谢谢 测试运行完成后一秒钟,Jest未退出 这通常意味着有一些异步操作在测试中没有停止。考虑使用运行jest-DeTeCopeNotos来解决这个问题。 test('Should be ', async () => { /*DO NOT call the next four function directly, check if a mer
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块周围以进行错误处理 谢谢,我已经在一个单独的javascript中声明了getMongoField函数,如何实现异步?谢谢你,PrashanOh,从那个文件中导出函数,并以'await function_name()'的形式运行,请确保运行此函数的父函数必须是异步的。我建议你查看有关async await和Promissions的资料。