【发布时间】:2019-11-23 21:45:09
【问题描述】:
我无法在 Typescript for Firebase Cloud Functions 中模拟 Firebase 消息传递函数。我正在使用firebase-functions-test Companion SDK 来构建docs 中提到的在线测试。我正在使用 jest mocks 来模拟 admin.messaging().sendToDevice 函数。
const fcmMock = jest.spyOn(admin.messaging(),'sendToDevice');
fcmMock.mockImplementation(async (registrationToken: string | string[], payload: admin.messaging.MessagingPayload, options?: admin.messaging.MessagingOptions)=>{
console.log('FCM Mock called with message: '+payload.notification+'\nToken ids:'+registrationToken);
return new Promise<admin.messaging.MessagingDevicesResponse>(undefined);
});
因为返回类型对象MessagingDevicesResponse>(undefined) 需要一个复杂的参数,所以运行它会得到以下错误:
'undefined' 类型的参数不能分配给 '(resolve: (value?: MessagingDevicesResponse | PromiseLike | undefined) => void, reject: (reason?: any) => void) => void' 类型的参数.
我要测试的代码:
export async function cleanupToken(response: admin.messaging.MessagingDevicesResponse, userDataSnapshot:FirebaseFirestore.DocumentSnapshot) {
// For each notification we check if there was an error.
if(response.results.length>0){
const error = response.results[0].error;
if (error) {
// Cleanup the tokens who are not registered anymore.
// Error Codes: https://firebase.google.com/docs/cloud-messaging/send-message#admin_sdk_error_reference
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
// Some Logic here to cleanup the token and mark the user
}
}
}
}
}
【问题讨论】:
标签: typescript firebase unit-testing firebase-cloud-messaging google-cloud-functions