【问题标题】:How to test Mongodb find,findOne function using Jest in NodeJS如何在 NodeJS 中使用 Jest 测试 Mongodb find、findOne 函数
【发布时间】:2019-10-09 23:02:06
【问题描述】:

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

我尝试使用 jest.fn() 模拟 find、findOne、UpdateMany mongo 函数的实现和返回值,但要么测试用例失败,要么我遇到“TypeError:无法读取未定义的属性” MongoDB 错误。需要很好的帮助来测试 mongoDB 的 find、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;
}

在我开玩笑的测试文件中:

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

}

【问题讨论】:

  • 您想尝试测试myService.myFuncImpl 以执行作为第二个参数传递给它的函数吗?
  • @nnfans - 是的,作为回调函数。我提到了这个 - jestjs.io/docs/en/mock-functions,它说你可以模拟和测试回调函数。
  • 你试过我下面的答案了吗?
  • 是的,它的工作。谢谢。
  • 请将其标记为答案

标签: javascript node.js mongodb typescript jestjs


【解决方案1】:

你必须返回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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2020-11-30
    • 2020-10-29
    • 1970-01-01
    • 2019-07-22
    • 2017-09-18
    相关资源
    最近更新 更多