Javascript 如何在NodeJS中使用Jest测试Mongodb find,findOne函数
我一直在尝试为我在代码中使用的mongodb find、findOne、UpdateMany系统库函数编写测试用例。但无法找到测试mongo函数的正确方法 我曾尝试使用jest.fn()模拟find、findOne、UpdateMany mongo函数的实现并返回其值,但要么测试用例失败,要么我遇到了“TypeError:无法读取未定义的”mongoDB错误的属性“s”。在测试mongoDB的findOne函数的正确方法上需要很好的帮助 我正在将mongo_con.find函数传递给myFuncImpl() 连接/配置文件:Javascript 如何在NodeJS中使用Jest测试Mongodb find,findOne函数,javascript,node.js,mongodb,typescript,jestjs,Javascript,Node.js,Mongodb,Typescript,Jestjs,我一直在尝试为我在代码中使用的mongodb find、findOne、UpdateMany系统库函数编写测试用例。但无法找到测试mongo函数的正确方法 我曾尝试使用jest.fn()模拟find、findOne、UpdateMany mongo函数的实现并返回其值,但要么测试用例失败,要么我遇到了“TypeError:无法读取未定义的”mongoDB错误的属性“s”。在测试mongoDB的findOne函数的正确方法上需要很好的帮助 我正在将mongo_con.find函数传递给myFunc
let mongo_conn = await MongoUtil.createMongoConnection(config.MONGO_COL_NAME);
myService.myFuncImpl(context,mongo_conn.find) // passing as a function
实施文件:
myFuncImpl = async (mongo_con_find:any) {
let result = await mongo_con_find({ }, { projection: {_id: 0, Name: 1 }}).toArray();
return result;
}
在我的jest测试文件中:
test("for myFuncImpl()", async () => {
let mongo_con_find = jest.fn(() => ({ toArray: _ =>[...DummyMongoResponse]}));
output_data = await myService.myFuncImpl(context_data,mongo_con_find)
expect(mongo_con_find).toHaveBeenCalledTimes(1); // giving me 0
}
你必须回报承诺才能使用等待
test("for myFuncImpl()", async () => {
let mongo_con_find = jest.fn(
() => ({
toArray: () => (new Promise(function(resolve, reject){
resolve([...DummyMongoResponse])
})
output_data = await myService.myFuncImpl(context_data,mongo_con_find)
expect(mongo_con_find).toHaveBeenCalledTimes(1); // giving me 0
}
是否尝试测试
myService.myFuncImpl
以执行作为第二个参数传递给它的函数?@nnfans-是,作为回调函数。我提到了这一点,它说你可以模拟和测试回调函数。你试过我下面的答案吗?是的,它可以工作。谢谢。请把它标记为答案