Setting up unit testing firebase functions (online mode).
I'm testing an onCreate() function, so I need to create a document in firestore to ensure the function is triggered and working properly. The problem I'm encountering is that testEnv.firestore.makeDocumentSnapshot(data, path) is not creating a new document. If the document already exists, I can write this data to it and trigger the onCreate() function, but if it doesn't exist I get an Error: 5 NOT_FOUND: No document to update when I run the test.
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});
});
I can fix this in makeLowerCase.ts by returning:
admin.firestore().doc(`animals/${snap.id}`).set({bio}, {merge: true});
Or by creating the doc with admin in the test:
await admin.firestore().doc(path).set(data);
But the testEnv.firestore.makeDocumentSnapshot(data, path); should be creating a document I think, no?
Is this is bug or expected behaviour from firebase-functions-test"?