firebase - 错误 : Wrap function is only available for `onCall` HTTP functions, 不是 `onRequest`

标签 firebase unit-testing google-cloud-functions

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

Error: Wrap function is only available for onCall HTTP functions, not 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);

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

谁能帮我解决这个问题吗?

最佳答案

单元测试包中的 wrap() 函数用于以后台事件云函数可以理解的方式重新格式化您传递给它的数据(这些函数具有一个处理程序签名,处理时看起来像 (data, context) => {}(context) => {})。您可以看到该函数正在做什么 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() 需要返回自身以进行链接)。对于这种情况,您最好使用快速单元测试库模拟请求和响应对象,然后将它们传递到要测试的函数中。

关于firebase - 错误 : Wrap function is only available for `onCall` HTTP functions, 不是 `onRequest`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70442193/

相关文章:

java - 如何使用 Firebase Auth 注销您的 Android Studio 帐户?

firebase - Angularfirecollection 返回对象而不是数组

android - Firebase 推送通知不使用来自 body_loc_key 的 Android 字符串资源

unit-testing - 未找到类 'Mockery'

unit-testing - Golang mockgen "does not implement"接口(interface)问题

audio - 上传到谷歌云存储时转换音频文件

java.lang.IllegalStateException : Failed to initialize a GAE background thread factory

c# - 最小起订量设置函数抛出异常不起作用

firebase - 使用 Firebase 函数将发布的表单图像缓冲区上传到 Cloud Storage

ios - 通过 Firebase 函数发送的 Swift 中的加密推送通知