You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Firebase Emulators在单元测试中调用Firebase Functions?

报错原因
  • 测试初始化的Firebase应用默认请求线上云端服务,没有指向本地运行的Functions模拟器,导致请求的云函数路径不存在,预检请求返回404状态码
  • 本地Firebase模拟器未启动Functions服务,或启动的Functions端口和测试请求的端口不匹配
  • 调用的云函数名称和本地模拟器中部署的函数名称不一致,或项目ID、资源名称配置不匹配
解决方法
  1. 初始化测试应用后手动指定Functions模拟器地址,默认端口为5001,如果你自定义了模拟器端口请对应修改:
const app = firebase.initializeTestApp({
  projectId: '你的项目ID', // 补充和本地模拟器一致的项目ID
  databaseName: 'mydb',
  auth: {
    uid: 'useruid'
  },
});
// 新增这行,指定本地Functions模拟器地址
app.functions().useEmulator('localhost', 5001);
  1. 启动Firebase模拟器时确认包含Functions服务,启动命令参考:
    firebase emulators:start --only functions,database
    启动后检查终端输出的Functions服务端口是否和测试代码中配置的一致。
  2. 核对调用的函数名称和你代码中导出的云函数名称完全一致,注意大小写敏感。
  3. 你当前测试用例是验证未认证用户调用失败的场景,但初始化的app已经绑定了auth用户信息,需要单独初始化无auth配置的测试app:
it('throws error if user is not authenticated', async () => {
  const unAuthApp = firebase.initializeTestApp({
    projectId: '你的项目ID',
    databaseName: 'mydb'
    // 不传入auth参数
  });
  unAuthApp.functions().useEmulator('localhost', 5001);
  const unAuthCloudfunction = unAuthApp.functions().httpsCallable('cloudfunction');
  await firebase.assertFail(unAuthCloudfunction())
})

内容的提问来源于stack exchange,提问作者Simon Tran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 16:39:05