'firestore tests depend on cloud function running

I have Cloud Firestore Function that runs every time a user is created to populate the database with some sample data.

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

admin.initializeApp();

const db = admin.firestore();

exports.createUser = functions.auth.user().onCreate((user) => {
  return db.collection("users").doc(user.uid).create({
    test: "test",
  });
});

But when I test it with my Firestore unit tests (with emulators running), then I get undefined when I query the sample data.

/**
 * @jest-environment node
 */
import fs from "fs";
import {
  initializeTestEnvironment,
  RulesTestEnvironment,
} from "@firebase/rules-unit-testing";
import { doc, getDoc } from "firebase/firestore";

const currentDate = new Date();
currentDate.setDate(currentDate.getDate() - 14);

let testEnv: RulesTestEnvironment;

beforeAll(async () => {
  testEnv = await initializeTestEnvironment({
    projectId: "comment-section-e9c09",
    firestore: {
      rules: fs.readFileSync("firestore.rules", "utf8"),
      host: "localhost",
      port: 8080,
    },
  });
});

beforeEach(async () => {
  await testEnv.clearFirestore();
});

afterAll(async () => {
  await testEnv.cleanup();
});

test("user can read sample data", async () => {
  const test_user_id = "test_user";
  const test_user = testEnv.authenticatedContext(test_user_id); //Cloud function is not run on user creation
  const test_user_db = test_user.firestore();

  const sampleData = await getDoc(doc(test_user_db, "users", test_user_id));

  expect(sampleData.data().foo).toBe("bar"); //sampleData.data() is undefined
});

Is there a way to make the Cloud Function run upon user creation using the test environment?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source