我正在尝试为我的 firebase 云功能设置单元测试。但出现此错误
Error: Wrap function is only available for
onCall
HTTP functions, notonRequest
.
这就是我的 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) => {}
的处理程序签名。因为这里没有进行任何花哨的处理,所以您可以直接传入您自己的 Request
和 Response
对象来调用该函数。 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.send
、res.status()
需要返回自身以进行链接)。对于这种情况,您最好使用快速单元测试库模拟请求和响应对象,然后将它们传递到要测试的函数中。
关于firebase - 错误 : Wrap function is only available for `onCall` HTTP functions, 不是 `onRequest`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70442193/