You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Functions Test无法包装v2函数,如何测试v2云函数?

Firebase云函数v2版本测试问题

我有两个Firebase云函数,hello是v1版本,hello2是v2版本,代码如下:

import { https } from "firebase-functions";
import { onCall } from "firebase-functions/v2/https";

export const hello = https.onCall((request) => {
  return `Hello ${request.data.text}`;
});

export const hello2 = onCall((request) => {
  return `Hello ${request.data.text}`;
});

使用firebase-functions-test SDK包装v1的hello没问题,但包装v2的hello2会报错。想问firebase-functions-test是不是只支持v1?该怎么测试v2函数?我的测试代码和错误信息如下:

import { hello, hello2 } from ".";
import { expect } from "chai";
import { wrap } from "firebase-functions-test/lib/main";

describe("hello function", () => {
  it("returns expected output", async () => {
    // Create a test request object.
    const request = {
      body: {
        text: "World",
      },
    };

    const wrapped = wrap(hello);
    // The following line fails with No overload matches this call.
    const wrapped2 = wrap(hello2);

    const response = await wrapped(request);
    // The following line fails with Argument of type '{ body: { text: string; }; }' is not assignable to parameter of type 'CallableRequest<any>'.
    const response2 = await wrapped2(request);

    expect(response).equal("Hello World");
    expect(response2).equal("Hello World");
  });
});

解答

firebase-functions-test支持v2版本云函数,只是测试v2函数的方式和v1存在差异,核心区别在于包装方法的导入路径和请求参数结构:

  1. v2函数的专用包装方法
    v2的onCall函数不能直接使用主模块的wrap()方法,需要导入v2专属的测试工具,从firebase-functions-test/v2/https路径获取wrap方法。

  2. v2函数的请求参数结构
    v2的CallableRequest参数结构与v1不同,不需要嵌套在body字段中,直接传入data对象即可——这和云函数内部读取参数的逻辑一致,v2函数里的request.data就是顶层属性。

修正后的测试代码

import { hello, hello2 } from ".";
import { expect } from "chai";
// 分别导入v1和v2对应的wrap方法
import { wrap as wrapV1 } from "firebase-functions-test/lib/main";
import { wrap as wrapV2 } from "firebase-functions-test/v2/https";

describe("hello function", () => {
  it("returns expected output for v1", async () => {
    const request = {
      body: {
        text: "World",
      },
    };
    const wrapped = wrapV1(hello);
    const response = await wrapped(request);
    expect(response).equal("Hello World");
  });

  it("returns expected output for v2", async () => {
    // v2直接传入data字段,无需body嵌套
    const request = {
      data: {
        text: "World",
      },
    };
    const wrapped2 = wrapV2(hello2);
    const response2 = await wrapped2(request);
    expect(response2).equal("Hello World");
  });
});

关键差异总结

  • 导入路径:v2的wrap方法来自firebase-functions-test/v2/https,v1的来自主模块
  • 请求结构:v1参数放在body中,v2直接放在data字段中

按上述方式修改后,即可正常测试v2版本的云函数。

内容的提问来源于stack exchange,提问作者Cupid Chan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:50:01