【发布时间】:2021-11-16 05:41:07
【问题描述】:
设置单元测试 firebase 功能(在线模式)。
我正在测试一个 onCreate() 函数,因此我需要在 firestore 中创建一个文档,以确保该函数被触发并正常工作。我遇到的问题是testEnv.firestore.makeDocumentSnapshot(data, path) 没有创建新文档。如果文档已经存在,我可以将这些数据写入其中并触发 onCreate() 函数,但如果它不存在,我会在运行测试时得到Error: 5 NOT_FOUND: No document to update。
test.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});
或者通过在测试中使用管理员创建文档:
await admin.firestore().doc(path).set(data);
但我认为testEnv.firestore.makeDocumentSnapshot(data, path); 应该正在创建一个文档,不是吗?
这是来自firebase-functions-test" 的错误还是预期行为?
【问题讨论】:
标签: javascript firebase unit-testing google-cloud-firestore google-cloud-functions