Firebase本地单元测试报错:无待更新实体,求解决方案
解决Firebase本地模拟器中Cloud Functions OnCreate测试的"NOT_FOUND"错误
核心问题定位
报错Error: 5 NOT_FOUND: no entity to update: app: "dev~not-a-project"的关键在于测试环境使用了默认占位项目ID(not-a-project),而非本地模拟器关联的实际测试项目ID,导致Firestore客户端无法定位到模拟器内的文档。
具体修复步骤
初始化测试用Firebase应用时指定项目ID
不要使用无参数的initializeApp(),显式传入与本地模拟器一致的项目ID(即firebase.json配置的项目ID或启动模拟器时--project参数指定的值):import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore"; const testApp = initializeApp({ projectId: "your-test-project-id" // 替换为你的测试项目ID }); const db = getFirestore(testApp);测试前在模拟器中创建目标文档
直接调用OnCreate函数时,模拟器不会自动生成触发文档(触发器仅监听真实写入操作),需在测试代码中先向Firestore模拟器写入对应文档:import { doc, setDoc } from "firebase/firestore"; // 测试前置操作:写入待更新的初始文档 await setDoc(doc(db, "your-collection", "your-doc-id"), { // 文档初始字段内容 }); // 调用OnCreate函数 await yourOnCreateFunction(snapshot, context);配置Firestore客户端指向本地模拟器
确保测试代码中的Firestore客户端连接到本地模拟器而非生产环境:import { connectFirestoreEmulator } from "firebase/firestore"; connectFirestoreEmulator(db, "localhost", 8080); // 端口与模拟器Firestore端口一致,默认8080确保函数内Firestore实例使用测试配置
若Cloud Functions代码使用默认getFirestore(),需在测试环境中让函数内部的Firestore指向模拟器,可通过设置环境变量实现:// 测试代码中设置环境变量,引导函数使用模拟器 process.env.FIRESTORE_EMULATOR_HOST = "localhost:8080";
额外注意事项
- 启动本地模拟器时,必须指定与测试代码一致的项目ID,例如:
firebase emulators:start --project your-test-project-id - 直接调用OnCreate函数时,需自行构造
snapshot和context对象,确保snapshot指向的文档已存在于模拟器中,可手动模拟或使用Firebase测试工具类生成:import { DocumentSnapshot } from "firebase/firestore"; // 模拟符合要求的DocumentSnapshot对象 const mockSnapshot = new DocumentSnapshot(/* 传入对应参数 */);
内容的提问来源于stack exchange,提问作者Gesichtsfelsen
相关产品推荐
相关产品推荐

