最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何在NodeJS中使用Jest测试Mongodb find,findOne函数

IT培训 admin 5浏览 0评论

如何在NodeJS中使用Jest测试Mongodb find,findOne函数

我一直在尝试为我的代码中使用的mongodb find,findOne,UpdateMany系统库函数编写测试用例。但是无法找到测试mongo函数的正确方法。

我尝试使用jest.fn()模拟实现并返回find,findOne,UpdateMany mongo函数的值,但是测试用例失败或卡在“ TypeError:无法读取未定义的属性's” mongoDB错误。需要正确的方法来测试mongoDB的findOne函数findOne的良好帮助。

我正在将mongo_con.find函数传递给myFuncImpl()

连接/配置文件:


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

}
回答如下:

您必须返回promise才能使用await

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

}

如何在NodeJS中使用Jest测试Mongodb find,findOne函数

我一直在尝试为我的代码中使用的mongodb find,findOne,UpdateMany系统库函数编写测试用例。但是无法找到测试mongo函数的正确方法。

我尝试使用jest.fn()模拟实现并返回find,findOne,UpdateMany mongo函数的值,但是测试用例失败或卡在“ TypeError:无法读取未定义的属性's” mongoDB错误。需要正确的方法来测试mongoDB的findOne函数findOne的良好帮助。

我正在将mongo_con.find函数传递给myFuncImpl()

连接/配置文件:


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

}
回答如下:

您必须返回promise才能使用await

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

}
发布评论

评论列表 (0)

  1. 暂无评论