繁体   English   中英

如何对 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;

所以测试本身运行但我遇到了问题,结果与我对 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关键字,但它对我不起作用。 是否需要将任何特定功能添加到资源中才能使 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!");
  });
});

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM