使用npm测试Firestore规则时出现127.0.0.1:8080连接拒绝错误
Firestore规则测试出现
connect ECONNREFUSED 127.0.0.1:8080错误的解决方法 问题背景
我需要验证以下Firestore安全规则的有效性:
service cloud.firestore { match /databases/{database}/documents { match /clubUsers/{uid} { allow read: if request.auth != null && request.auth.uid == uid; allow create: if request.auth != null && request.auth.uid == uid; allow update: if request.auth != null && request.auth.uid == uid; } } }
使用Jest和Firebase测试工具编写了如下测试脚本:
const firebase = require('@firebase/testing/'); const fs = require('fs'); const project_id = "PROJECT ID"; describe("testing firestore rules", () => { beforeAll( async () => { await firebase.loadFirestoreRules({ projectId: project_id, rules: fs.readFileSync('../../firestore.rules', 'utf8'), }); } ); afterEach( async () => { await firebase.clearFirestoreData({ projectId: project_id }); } ); afterAll( async () => { await Promise.all( firebase.apps().map((app) => app.delete()) ); } ); function authedApp(auth) { return firebase.initializeTestApp({ projectId: project_id, auth: auth, }).firestore(); } describe("testing get and write", () => { test("testing get", async () => { const db = authedApp({ uid: 'UID' }); const message = db.collection("clubUsers").doc("UID"); await firebase.assertSucceeds(message.get()); }) test("testing write", async () => { const db = authedApp({ uid: "UID" }); const message = db.collection("clubUsers").doc("UID"); await firebase.assertSucceeds( message.set({ text: "hoge" }) ); }) }) })
执行npm test时抛出错误:connect ECONNREFUSED 127.0.0.1:8080,已确认Firebase模拟器处于启动状态,但通过sudo lsof -P -i:8080检查发现该端口未被占用,需要解决该问题。
解决方法
1. 确认Firestore模拟器的实际端口
Firebase新版本中,Firestore模拟器默认端口可能不是8080(比如5002)。查看模拟器启动日志,找到Firestore服务的实际运行端口,日志示例:
firestore: Firestore Emulator logging to firestore-debug.log
firestore: Emulator running on 127.0.0.1:5002
2. 在测试脚本中指定模拟器端口
修改测试代码,显式指定Firestore模拟器的地址,两种方式二选一:
- 方式一:通过环境变量指定
// 在文件顶部添加 process.env.FIRESTORE_EMULATOR_HOST = "127.0.0.1:5002"; // 替换为你的实际端口
- 方式二:在初始化Firestore实例时指定
function authedApp(auth) { const app = firebase.initializeTestApp({ projectId: project_id, auth: auth, }); const db = app.firestore(); db.settings({ host: "127.0.0.1:5002", // 替换为实际端口 ssl: false }); return db; }
3. 检查模拟器启动命令
确保启动模拟器时明确包含Firestore服务,使用正确的启动命令:
firebase emulators:start --only firestore
如果需要同时运行其他服务,可调整--only参数,比如--only firestore,auth。
4. 修复模拟器进程异常
如果日志显示端口为8080但lsof检测不到占用,可能是模拟器进程异常:
- 杀死所有Firebase相关进程:
pkill -f firebase - 重新启动模拟器:
firebase emulators:start --only firestore - 再次用
netstat -tulpn | grep 8080检查端口占用情况。
5. 验证文件路径与依赖版本
- 确认
fs.readFileSync('../../firestore.rules', 'utf8')的路径正确,避免因规则文件找不到导致的间接错误。 - 同步
@firebase/testing与firebase-tools版本,更新到稳定版:
npm update @firebase/testing firebase-tools
内容的提问来源于stack exchange,提问作者Itsu
相关产品推荐
相关产品推荐

