【问题标题】:Error: Wrap function is only available for `onCall` HTTP functions, not `onRequest`错误:包装函数仅适用于 `onCall` HTTP 函数,不适用于 `onRequest`
【发布时间】:2022-01-23 06:33:12
【问题描述】:

我正在尝试为我的 firebase 云功能设置单元测试。但收到此错误

错误:Wrap 函数仅适用于 onCall HTTP 函数,不适用于 onRequest

这就是我的 app.test.ts 的样子

/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {stub} from "sinon";
import * as admin from "firebase-admin";
import funcTest from "firebase-functions-test";
admin.initializeApp();

describe("Index Test", function() {
  let adminInitStub:any;
  let appCloudFunction:any;
  const test = funcTest();
  before(async () => {
    adminInitStub = stub(admin, "initializeApp");
    appCloudFunction = await import("../index");
  });

  after(() => {
    adminInitStub.restore();
    test.cleanup();
  });
  it("should always pass", function() {
    const wrapped = test.wrap(appCloudFunction.app);
    wrapped(null);
  });
});

我的云函数(index.ts)看起来像这样

import * as functions from "firebase-functions";
import app from "./app/app";
exports.app = functions.https.onRequest(app);

这里的应用程序是一个简单的快速应用程序。

谁能帮我解决这个问题?

【问题讨论】:

  • 我认为错误信息很清楚。不支持您尝试执行的操作。如果您有添加对 onRequest 支持的功能请求,则应直接向 Firebase 提出问题。 Stack Overflow 帮不了你。

标签: firebase unit-testing google-cloud-functions


【解决方案1】:

单元测试包中的wrap() 函数用于以后台事件云函数可以理解的方式重新格式化传递给它的数据(这些函数的处理程序签名类似于(data, context) => {} 或@ 987654325@) 处理时。你可以看到函数在做什么here

“原始”HTTPS 请求函数具有类似于 (request, response) => {} 的处理程序签名。因为这里没有花哨的处理,你可以直接调用函数,直接传入你自己的RequestResponse对象。 documentation 对此有更多详细信息。

// index.js
export myTestFunction = functions.https.onRequest(myExpressApp);
// index.test.js
import { myTestFunction } from "./index.js"

const req = {
  url: "https://example.com/path/to/test",
  query: {
    "id": "10"
  }
}

const res = {
  status: () => {} // your test shim
  json: () => {} // your test shim
}

myTestFunction(req, res);

// wait for res to be processed
// do tests

您可能会遇到以这种方式传递如此简单的响应对象的问题,因为您在 Cloud Function 后面使用 Express 并且它执行大量内部函数调用(例如,res.json 会调用 res.sendres.status() 需要返回自身进行链接)。对于这种情况,您最好使用快速单元测试库模拟 Request 和 Response 对象,然后将它们传递给您的函数进行测试。

【讨论】:

    猜你喜欢
    • 2022-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2013-07-08
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多