时间戳方法"/>
如何在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时间戳方法
发布评论