testEnv.firestore.makeDocumentSnapshot(data, path) 没有创建新文档

testEnv.firestore.makeDocumentSnapshot(data, path) is not creating a new document

设置单元测试 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" 的错误还是预期行为?

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();