如何在Jest和NestJS中模拟toDate时间戳方法

编程入门 行业动态 更新时间:2024-10-09 11:27:35

如何在Jest和NestJS中模拟toDate<a href=https://www.elefans.com/category/jswz/34/1771441.html style=时间戳方法"/>

如何在Jest和NestJS中模拟toDate时间戳方法

我正在尝试(开玩笑地)测试一个使用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()方法,则测试有效。有人知道发生了什么吗?

回答如下:您的模拟数据需要具有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()是可调用的方法,该方法返回您期望的结果。

更多推荐

如何在Jest和NestJS中模拟toDate时间戳方法

本文发布于:2024-05-07 12:28:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   方法   如何在   NestJS   Jest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!