設定單元測驗 firebase 功能(在線模式)。
我正在測驗一個 onCreate() 函式,所以我需要在 firestore 中創建一個檔案以確保該函式被觸發并正常作業。我遇到的問題testEnv.firestore.makeDocumentSnapshot(data, path)是沒有創建新檔案。如果檔案已經存在,我可以將這些資料寫入它并觸發 onCreate() 函式,但如果它不存在,我會Error: 5 NOT_FOUND: No document to update在運行測驗時得到一個。
測驗.ts
const functions = require("firebase-functions-test");
const testEnv = functions({
databaseURL: "https://***.firebaseio.com",
storageBucket: "***.appspot.com",
projectId: "***",
}, "./test-service-account.json");
import "jest";
import * as admin from "firebase-admin";
import { makeLowerCase } from "../src";
describe("makes bio lower case", () => {
let wrapped: any;
beforeAll(() => {
wrapped = testEnv.wrap(makeLowerCase);
});
test("it converts the bio to lowercase", async () => {
const path = "/animals/giraffe";
const data = {bio: "GIRAFFE"};
const snap = testEnv.firestore.makeDocumentSnapshot(data, path);
await wrapped(snap)
const after = await admin.firestore().doc(path).get();
expect(after?.data()?.bio).toBe("giraffe");
});
});
makeLowerCase.ts
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
export const makeLowerCase = functions.firestore
.document("animals/{animalId}")
.onCreate((snap, context) => {
const data = snap.data();
const bio = data.bio.toLowerCase();
return admin.firestore().doc(`animals/${snap.id}`).update({bio});
});
我可以makeLowerCase.ts通過回傳來解決這個問題:
admin.firestore().doc(`animals/${snap.id}`).set({bio}, {merge: true});
或者通過在測驗中使用 admin 創建檔案:
await admin.firestore().doc(path).set(data);
但是testEnv.firestore.makeDocumentSnapshot(data, path);我認為應該創建一個檔案,不是嗎?
這是錯誤還是預期的行為firebase-functions-test"?
uj5u.com熱心網友回復:
makeDocumentSnapshot(data, path)不會創建實際的檔案,它只會在QueryDocumentSnapshot不與任何實際資料庫互動的情況下欺騙物件 - 將其視為“制作 DocumentSnapshot 物件”。
雖然您的 Cloud Function 可以正確地假設該檔案確實存在,因為它就是這樣觸發的,但如果您希望繼續使用update(...)而不是set(..., { merge: true }).
所以你至少需要添加:
await admin.firestore().doc(path).set(data);
然后您可以使用以下任一方法:
const snap = testEnv.firestore.makeDocumentSnapshot(data, path);
// OR
const snap = await admin.firestore().doc(path).get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359936.html
標籤:javascript 火力基地 单元测试 谷歌云firestore 谷歌云功能
上一篇:AngularKarmaJasmine單元測驗AfterAllTypeError中拋出錯誤:users.forEach不是函式
