【问题标题】:testEnv.firestore.makeDocumentSnapshot(data, path) is not creating a new documenttestEnv.firestore.makeDocumentSnapshot(data, path) 没有创建新文档
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-05-06
      • 2021-03-21
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多