【问题标题】:How to mock toDate Timestap method in Jest and NestJS如何在 Jest 和 NestJS 中模拟 toDate Timestamp 方法
【发布时间】:2020-08-28 15:25:36
【问题描述】:

我正在尝试(开玩笑地)测试一个使用 firebase 尽可能获取用户数据的控制器 见下一个例子


    const queryPersonalInfo = (
      await firebase
        .firestore()
        .collection('users')
        .doc(user)
        .get()
    ).data();


    const strokeInfo: StrokeInfo = {
      birthDay: queryPersonalInfo.birthday.toDate(),
      height: queryPersonalInfo.height,
      weight: queryPersonalInfo.weight,
      hypertensive: queryPersonalInfo.hypertensive,
      smoker: queryPersonalInfo.smoker,
      fa: lastUserRecord.hasAnomaly,
    };

    return this.strokeRiskService.calculateStrokeRisk(strokeInfo);
  }
}

如图所示,我模拟了firebase-admin

  initializeApp: jest.fn(),
  firestore: () => ({
    collection: jest.fn(collectionName => ({
      doc: jest.fn(docName => ({
        get: jest.fn(() => ({
          data: jest.fn().mockReturnValue({
            birhtday: "2020-05-05T10:53:47.414Z",
            height: 180,
            weight: 80,
            hypertensive: true,
            smoker: true,
            fa: true,
            diabetic: false,
          }),
        })),
      })),
    })),
  }),  
})); 

但测试失败,因为无法识别 toDate() 方法。

TypeError: Cannot read property 'toDate' of undefined

      48 |     console.log(queryPersonalInfo);
      49 |     const strokeInfo: StrokeInfo = {
    > 50 |       birthDay: queryPersonalInfo.birthday.toDate(),
         |                                            ^
      51 |       height: queryPersonalInfo.height,
      52 |       weight: queryPersonalInfo.weight,
      53 |       hypertensive: queryPersonalInfo.hypertensive,

      at StrokeRiskController.getStrokeRisk (stroke-risk/stroke-risk.controller.ts:50:44)

如果我删除 toDate() 方法,则测试有效。 有谁知道怎么回事?

【问题讨论】:

  • 您在birhtday 中有错字。

标签: node.js firebase unit-testing jestjs nestjs


【解决方案1】:

您的模拟数据需要将birthday 属性作为具有toDate 方法的对象。它可能看起来像这样:

  initializeApp: jest.fn(),
  firestore: () => ({
    collection: jest.fn(collectionName => ({
      doc: jest.fn(docName => ({
        get: jest.fn(() => ({
          data: jest.fn().mockReturnValue({
            birthday: {
              toDate: () => "2020-05-05T10:53:47.414Z",
            },
            height: 180,
            weight: 80,
            hypertensive: true,
            smoker: true,
            fa: true,
            diabetic: false,
          }),
        })),
      })),
    })),
  }),  
}));

这将确保queryPersonalInfo.birthday.toDate() 是一个可调用的方法,可以返回您期望的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 2023-02-15
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2021-06-14
    相关资源
    最近更新 更多