Node.js 如何在Jest和NestJS中模拟toDate Timestap方法
我正在尝试测试(使用jest)一个控制器,它使用firebase尽可能获取用户数据 请参见下一个示例Node.js 如何在Jest和NestJS中模拟toDate Timestap方法,node.js,firebase,unit-testing,jestjs,nestjs,Node.js,Firebase,Unit Testing,Jestjs,Nestjs,我正在尝试测试(使用jest)一个控制器,它使用firebase尽可能获取用户数据 请参见下一个示例 const queryPersonalInfo = ( await firebase .firestore() .collection('users') .doc(user) .get() ).data(); const strokeInfo: StrokeInfo = { bi
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()方法
如果我删除toDate()
方法,测试就会工作。
有人知道发生了什么吗?您的模拟数据需要将
生日
属性作为具有toDate
方法的对象。它可以看起来像这样:
初始化app:jest.fn(),
firestore:()=>({
集合:jest.fn(collectionName=>({
doc:jest.fn(docName=>({
get:jest.fn(()=>({
数据:jest.fn().mockReturnValue({
生日:{
toDate:()=>“2020-05-05T10:53:47.414Z”,
},
身高:180,
体重:80,
高血压:是的,
吸烟者:是的,
法:是的,
糖尿病患者:错,
}),
})),
})),
})),
}),
}));
这将确保
queryPersonalInfo.birth.toDate()
是一个可调用的方法,它返回您期望的结果。您在birhtday
中有一个输入错误。
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)