如何在Jest和NestJS中模拟toDate Timestap方法

时间:2020-05-12 17:03:53

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

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

1 个答案:

答案 0 :(得分: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()是可调用的方法,该方法可返回您期望的结果。