求助:Cypress无法连接Firestore模拟器该如何解决?
解决Cypress无法连接Firestore模拟器及获取数据问题
以下是针对你遇到的问题的具体解决步骤:
1. 调整Firebase模拟器连接逻辑
现有配置依赖window.location.hostname === "localhost"判断是否连接模拟器,但Cypress运行时可能出现hostname不符合的情况(比如部分环境下用127.0.0.1或Cypress内部域名)。改用Cypress内置标识强制测试环境连接模拟器:
import { initializeApp } from "firebase/app"; import { getFirestore, connectFirestoreEmulator } from "firebase/firestore"; // 若使用实时数据库,需引入对应模块 // import { getDatabase, connectDatabaseEmulator } from "firebase/database"; const firebaseApp = initializeApp({ // 你的Firebase配置内容 }); const db = getFirestore(firebaseApp); // 同时兼容本地开发和Cypress测试环境 if (window.location.hostname === "localhost" || window.Cypress) { connectFirestoreEmulator(db, "localhost", 8080); // 实时数据库模拟器连接(若使用) // const realtimeDb = getDatabase(firebaseApp); // connectDatabaseEmulator(realtimeDb, "localhost", 9000); } export default db;
2. 配置Cypress跨域与网络权限
Cypress默认安全策略会限制跨域请求,需在cypress.config.js中允许访问模拟器端口:
const { defineConfig } = require("cypress"); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { // 自定义节点事件逻辑(如有) }, chromeWebSecurity: false, // 解除跨域限制 allowedOrigins: ["http://localhost:8080", "http://localhost:9000"] // 允许模拟器地址 }, });
3. 确保模拟器在测试前启动
必须保证Firestore(及实时数据库)模拟器在Cypress测试运行前处于启动状态,可通过package.json脚本整合启动流程:
{ "scripts": { "test:e2e": "firebase emulators:start --only firestore,database & cypress run", "test:e2e:open": "firebase emulators:start --only firestore,database & cypress open" } }
执行npm run test:e2e或npm run test:e2e:open即可先启动模拟器,再运行Cypress测试。
4. 验证请求是否指向模拟器
在Cypress测试中添加请求拦截,确认数据请求发向模拟器而非正式Firebase服务器:
it("验证连接Firestore模拟器", () => { cy.intercept("POST", "http://localhost:8080/**").as("firestoreReq"); cy.visit("/"); // 访问你的应用页面 cy.wait("@firestoreReq").then(interception => { expect(interception.request.url).to.include("localhost:8080"); }); });
5. 检查模拟器权限规则
确保Firestore模拟器的规则允许数据读取,临时放宽规则便于测试:
在firestore.rules中设置:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if true; // 测试环境下允许所有操作 } } }
内容的提问来源于stack exchange,提问作者user19786344
相关产品推荐
相关产品推荐

