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

Firestore单元测试报错:期望DocumentReference却得到自定义对象

问题原因及解决方案

核心问题

你调用setDoc时传错了参数类型:setDoc的第一个参数要求是DocumentReference(文档引用),但你直接传入了alice.firestore()返回的Firestore实例,导致类型不匹配错误。

修正步骤

  1. 从@firebase/firestore导入doc方法,用于生成文档引用
  2. 用doc()方法从Firestore实例构造目标文档的引用,再传入setDoc

修正后的测试代码

import { getDoc, setDoc, doc } from "@firebase/firestore"; // 新增doc导入
import {
  assertFails,
  assertSucceeds,
  initializeTestEnvironment,
  RulesTestEnvironment,
} from "@firebase/rules-unit-testing"

describe('Creating a user', () => {
  let alice;
  let anon;
  let testEnv;

  beforeAll(async () => {
    testEnv = await initializeTestEnvironment({
      projectId: "PROJECT_ID"
    })
  })

  beforeEach(() => {
    alice = testEnv.authenticatedContext("alice", { user_id: "1" });
    anon = testEnv.unauthenticatedContext();
  });

  test('alice can create a user', async () => {
    // 用doc()构造文档引用,替换直接传Firestore实例的写法
    await assertSucceeds(setDoc(doc(alice.firestore(), 'users/alice'), { "name": "alice" }));
  })
});

补充说明

官方示例代码里的写法属于简化表述,实际使用时必须通过doc()方法明确生成DocumentReference。你的npm依赖版本是兼容的,无需调整版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:02:11