如何在 Firebase Cloud Functions 测试中模拟 FCM admin.messaging().sen



我无法在 Typescript for Firebase Cloud Functions 中模拟 Firebase 消息传递函数。我正在使用 firebase-functions-test 配套 SDK 来构建文档中提到的在线测试。我正在使用开玩笑的模拟来模拟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"的参数不能分配给类型为"(解析:(值?:消息传递设备响应|承诺 |未定义( => 无效,拒绝:(原因?:任何(=> 无效( => 无效"。

我将要测试的代码:


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

查看您的代码,缺少/不正确:

    change jest.spyOn(admin.messaging((,'sendToDevice'(;
  1. to jest.spyOn(admin,'sendToDevice'(;
  2. 传入模拟对象,在本例中为响应和快照

    // 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. 您不会在 jest 测试用例中返回 promise,而是使用 jest 测试方法(在本例中为 expect(。

  4. 通常,开玩笑测试(在这种情况下是期望(可以在函数中完成,但我们是在响应中进行的,因为这是回调,因此它发生在最后。

您的测试用例应如下所示:

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

相关内容

  • 没有找到相关文章

最新更新