Firestore 的玩笑:ReferenceError:初始化前无法访问“对象”

问题描述 投票:0回答:1

我在模拟 Firebase 功能的玩笑测试时遇到问题

roleService.unit.test

import { RoleService } from "../../services/RoleService";
import { CustomError } from "../../exceptions/custom_error";

const mockGet = jest.fn();
const mockDoc = jest.fn().mockReturnValue({ get: mockGet });
const mockCollection = jest.fn().mockReturnValue({ doc: mockDoc });
const mockFirestore = jest.fn().mockReturnValue({ collection: mockCollection });

jest.mock("firebase-admin", () => ({
  firestore: jest.fn().mockReturnValue(mockFirestore()),
}));

describe("RoleService Unit Tests", () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  test("should throw error when role does not exist", async () => {
    const roleId = "role123";

    mockGet.mockResolvedValue({
      exists: false,
      data: jest.fn().mockReturnValue(null),
      id: roleId,
    });

    await expect(RoleService.getRoleById(roleId)).rejects.toThrow(CustomError.roleNotFound());
  });
});

当我跑步时:

npm test --detectOpenHandles

出现此错误:

Test suite failed to run

    ReferenceError: Cannot access 'mockFirestore' before initialization

       8 |
       9 | jest.mock("firebase-admin", () => ({
    > 10 |   firestore: jest.fn().mockReturnValue(mockFirestore()),
         |                                        ^
      11 | }));
      12 |
      13 | describe("RoleService Unit Tests", () =>
firebase unit-testing jestjs
1个回答
0
投票

几个小时后,在这里发布我的问题后,我发现我做错了什么

我只是设置了箭头功能

jest.mock("firebase-admin", () => ({
  firestore: () => mockFirestore(),
}));
© www.soinside.com 2019 - 2024. All rights reserved.