如何在GitHub Actions中协调Firebase Emulator与Vitest的执行顺序?
解决方案
核心问题在于你拆分的两个Job运行在独立的GitHub Actions虚拟机上,无法共享端口;且第一个Job因Firebase模拟器持续运行无法进入完成状态,导致第二个Job永远无法触发。正确的做法是将模拟器启动、等待就绪、测试执行、模拟器停止全流程放在同一个Job中完成。
方案一:手动控制模拟器生命周期
更新你的GitHub Actions配置文件如下:
name: Run Tests on: pull_request: branches: [develop] workflow_dispatch: jobs: test-with-emulator: name: Run Tests with Firebase Emulator runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Use Node.js 18.14.0 uses: actions/setup-node@v3 with: node-version: 18.14.0 cache: 'npm' - name: Install Dependencies env: VITE_RELEASE_STAGE: testing run: | npm ci npm install --save firebase-tools - name: Start Firebase Emulator in Background env: VITE_RELEASE_STAGE: testing run: | # 后台启动模拟器,将日志输出到文件,记录进程ID npm run emulators > emulator.log 2>&1 & echo "$!" > emulator.pid - name: Wait for Emulator to Be Ready run: | # 检测Firebase模拟器默认端口(以Firestore的8080为例,根据你的实际配置修改) until nc -z localhost 8080; do echo "Waiting for emulator to start..." sleep 2 done echo "Emulator is ready!" - name: Run Unit Tests env: VITE_RELEASE_STAGE: testing run: | npm run test - name: Stop Firebase Emulator if: always() # 无论测试成功/失败,都强制停止模拟器 run: | kill $(cat emulator.pid) || true
关键细节
- 后台启动模拟器:用
&将模拟器进程放入后台运行,同时记录进程ID到文件,方便后续停止;日志输出到文件便于调试。 - 端口就绪检测:使用
nc(netcat)工具循环检测模拟器端口,直到端口开放再执行测试。如果你的模拟器使用其他端口(如Auth的9099、Database的9000),请修改对应的端口号。 - 统一Job执行:确保模拟器和测试在同一虚拟机环境,端口可直接访问。
- 强制停止模拟器:
if: always()保证无论测试结果如何,都会终止模拟器进程,避免资源浪费。
如果运行环境未预装nc,可在等待步骤前添加安装命令:
sudo apt-get update && sudo apt-get install -y netcat
方案二:使用Firebase官方命令简化流程
Firebase提供了firebase emulators:exec命令,可自动处理模拟器启动、等待就绪、运行指定任务、停止模拟器的全流程,配置更简洁。
- 修改
package.json中的脚本:
"test": "vitest", "test-with-emulator": "firebase emulators:exec --project celebrityfanalizer --import emulatorData \"npm run test\""
- 简化GitHub Actions配置:
name: Run Tests on: pull_request: branches: [develop] workflow_dispatch: jobs: test-with-emulator: name: Run Tests with Firebase Emulator runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Use Node.js 18.14.0 uses: actions/setup-node@v3 with: node-version: 18.14.0 cache: 'npm' - name: Install Dependencies env: VITE_RELEASE_STAGE: testing run: | npm ci npm install --save firebase-tools - name: Run Tests with Emulator env: VITE_RELEASE_STAGE: testing run: | npm run test-with-emulator
这个方案无需手动处理进程和端口检测,由Firebase工具自动完成,更省心可靠。
内容的提问来源于stack exchange,提问作者ARNON
相关产品推荐
相关产品推荐

