简体   繁体   English

如何在 Firebase Cloud Functions 测试中模拟 FCM admin.messaging().sendToDevice() 的实现

[英]How to mock implementation for FCM admin.messaging().sendToDevice() in Firebase Cloud Functions Tests

I'm unable to mock the Firebase Messaging functions in Typescript for Firebase Cloud Functions.我无法模拟 Firebase Cloud Functions 的 Typescript 中的 Firebase 消息传递函数。 I'm using firebase-functions-test Companion SDK to build Online Tests as mentioned in the docs .我正在使用firebase-functions-test Companion SDK 来构建文档中提到的在线测试。 I'm using jest mocks to mock the admin.messaging().sendToDevice function.我正在使用 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);
}); 

Running this gets the following error because the return type object MessagingDevicesResponse>(undefined) requires a complex argument:运行它会得到以下错误,因为返回类型对象MessagingDevicesResponse>(undefined)需要一个复杂的参数:

Argument of type 'undefined' is not assignable to parameter of type '(resolve: (value?: MessagingDevicesResponse | PromiseLike | undefined) => void, reject: (reason?: any) => void) => void'. 'undefined' 类型的参数不能分配给 '(resolve: (value?: MessagingDevicesResponse | PromiseLike | undefined) => void, reject: (reason?: any) => void) => void' 类型的参数。

The code I'm going to test:我要测试的代码:


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
                }
            }
        }
    }
}

looking at your code there are a few things missing/incorrect:查看您的代码,有一些缺失/不正确的地方:

  1. change jest.spyOn(admin.messaging(),'sendToDevice');更改 jest.spyOn(admin.messaging(),'sendToDevice'); to jest.spyOn(admin,'sendToDevice'); to jest.spyOn(admin,'sendToDevice');
  2. pass in mock objects, in this case response and snapshot传入模拟对象,在本例中为响应和快照

    // A fake response object, with a send to test the response const res = { send: (response) => { expect(response).toBe("Hello from Firebase!"); done(); } }; //how to create a datasnapshot. Takes in 2 parameters, the object and the reference path const userDataSnapshot = test.database.makeDataSnapshot(Object,'ref/to-the/path');
  3. you dont return a promise in a jest test case, instead you use the jest test method (in this case expect).您不会在玩笑测试用例中返回承诺,而是使用玩笑测试方法(在本例中为expect)。

  4. Normally the jest test (expect in this case) can be done in the function but we are doing it in the response since that is the callback hence it takes place right at the end.通常开玩笑测试(在这种情况下是预期的)可以在函数中完成,但我们在响应中进行,因为这是回调,因此它发生在最后。

You test case should look something like this:你的测试用例应该是这样的:

describe('testing jest functions',() =>{
  let index,adminStub;


  //setup test enviroment
  beforeAll(() =>{
      adminStub = jest.spyOn(admin, "initializeApp");
      index = require('./index');

      return;
  });

  //tear down
  afterAll(() =>{
    adminStub.mockRestore();
    testEnv.cleanup();
  });

  it('test cleanupToken function', (done) =>{

        const res = {
              send: (response) => {
                    //assuming you use response.send in your actual code you can test it
                  expect(response).toBe("Hello from Firebase!");
                  done();
                  }
              };

        const userDataSnapshot = test.database.makeDataSnapshot(Object,'ref/to-the/path');

      index.cleanupToken(res,userDataSnapshot);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Firebase 云函数中模拟辅助函数? - How to mock helper functions in Firebase Cloud Functions? 在 firebase 云功能中具有 typescript 的 firebase-admin - firebase-admin with typescript in firebase cloud functions 如何使用打字稿初始化Firebase云功能中的管理员凭据? - How to initialize admin credentials in Firebase cloud functions, using typescript? 如何使用TypeScript在Cloud函数中使用Admin SDK从Firebase读取数据 - how to read data from firebase with admin sdk in cloud functions with typescript Firebase Cloud Functions 上的“尝试对 FCM 服务器进行身份验证时发生错误” - 'An error occurred when trying to authenticate to the FCM servers' on Firebase Cloud Functions 如何在Angular2中实例化Firebase云消息传递 - How to instantiate Firebase Cloud Messaging in Angular2 如何清除下一个测试的Jest模拟实现? - How to clear Jest mock implementation for next tests? 在 Firebase 云函数中找不到 admin.database.ServerValue - admin.database.ServerValue not found in Firebase cloud functions 如何在 Firebase 云函数 Typescript 中定义 const - How to define const in Firebase Cloud Functions Typescript 如何在 Firebase 云函数中存储记录 ID - How to store ID of record in Firebase cloud functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM