如何对 onCall firebase 云功能进行单元测试?

How to unit test onCall firebase cloud functions?

我正在尝试为 firebase 云函数编写我的第一个单元测试,特别是用于 firebase 移动 SDK 的 https.onCall 函数。所以我尝试使用在线示例编写它并得到了这个结果代码:

import "jest";
import helloWorld from "../src/functions/helloworld";
import Message from "../src/types/message";

describe("helloworld", () => {
  test("it should run", () => {
    const req = { body: { data: {} } };
    const res = {
      on: (response: Message) => {
        expect(response).toBe({ text: "Hello from Firebase!", code: 200 });
      },
    };

    helloWorld(req as any, res as any);
  });
});

以防万一我在函数本身做错了什么,我将在这里分享函数的代码:

import { logger, region, https } from "firebase-functions/v1";
import Message from "../types/message";

const helloWorldHandler = region("europe-west1").https.onCall((_, context) => {
  if (context.app == undefined) {
    throw new https.HttpsError("failed-precondition", "The function must be called from an App Check verified app.");
  }

  logger.info("Hello logs!", { structuredData: true });
  const message: Message = {
    text: "Hello from Firebase!",
    code: 200,
  };
  return message;
});

export default helloWorldHandler;

所以测试本身 运行s 但是我 运行 进入了这个问题,结果与我对 toBe

的期望不同

我收到以下错误:

matcherResult: {
    actual: 'finish',
    expected: { text: 'Hello from Firebase!', code: 200 },
    message: '\x1B[2mexpect(\x1B[22m\x1B[31mreceived\x1B[39m\x1B[2m).\x1B[22mtoBe\x1B[2m(\x1B[22m\x1B[32mexpected\x1B[39m\x1B[2m) // Object.is equality\x1B[22m\n' +
      '\n' +
      'Expected: \x1B[32m{"code": 200, "text": "Hello from Firebase!"}\x1B[39m\n' +
      'Received: \x1B[31m"finish"\x1B[39m',
    name: 'toBe',
    pass: false
  }

我猜res上的on函数是错误的,应该是不同的。尽管如此,firebase 在其文档中提供的唯一示例是使用 redirect, 的函数,所以我想我需要另一个关键字,因为 on 不是正确的关键字。我也尝试使用 send 关键字,但它对我不起作用。是否需要将任何特定功能添加到 res 才能使 OnCall 正常工作,或者我是否还有其他一般性问题?

上面的代码大体上是不正确的。使用下面的代码,我的单元测试工作正常。将更改问题名称以便其他人可以更轻松地找到它:

import * as functions from "firebase-functions-test";
import helloWorldHandler from "../src/functions/helloworld";
import Message from "../src/types/message";

describe('Testing "helloWorld"', () => {
  it("test helloWorld if function works", async () => {
    const test = functions();
    const data = {};
    const context = {
      app: {},
    };
    const result: Message = await test.wrap(helloWorldHandler)(data, context);
    expect(result.code).toBe(200);
    expect(result.text).toBe("Hello from Firebase!");
  });
});