![](/img/trans.png)
[英]How to test `functions.https.onCall` firebase cloud functions locally?
[英]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.