首页 > 解决方案 > 在 Jest 中模拟 Firebase 管理员时出错:“TypeError:admin.firestore 不是函数”

问题描述

我有一个函数来处理通过 Admin SDK 连接到 Cloud Firestore。我知道该功能工作正常,因为应用程序连接并允许写入数据库。

现在我正在尝试用 Jest 测试这个功能。为避免在此功能范围之外进行测试,我正在模拟 firebase-admin 节点模块。但是,我的测试失败并出现错误“TypeError:admin.firestore 不是函数”。

我的函数和测试都是用 TypeScript 编写的,通过 ts-jest 运行,但我认为这不是 TypeScript 错误,因为 VS Code 没有任何抱怨。我相信这是 Jest 自动模拟的问题。

admin.firebase()是一个有效的调用。TypeScript 定义文件将其定义为function firestore(app?: admin.app.App): admin.firestore.Firestore;

我已经阅读了 Jest 文档,但我不明白如何解决这个问题。

这是我的功能:

// /src/lib/database.ts

import * as admin from "firebase-admin"

/**
 * Connect to the database
 * @param key - a base64 encoded JSON string of serviceAccountKey.json
 * @returns - a Cloud Firestore database connection
 */
export function connectToDatabase(key: string): FirebaseFirestore.Firestore {
  // irrelevant code to convert the key

  try {
    admin.initializeApp({
      credential: admin.credential.cert(key),
    })
  } catch (error) {
    throw new Error(`Firebase initialization failed. ${error.message}`)
  }

  return admin.firestore() // this is where it throws the error
}

这是我的测试代码:

// /tests/lib/database.spec.ts

jest.mock("firebase-admin")
import * as admin from "firebase-admin"
import { connectToDatabase } from "@/lib/database"

describe("database connector", () => {
  it("should connect to Firebase when given valid credentials", () => {
    const key = "ewogICJkdW1teSI6ICJUaGlzIGlzIGp1c3QgYSBkdW1teSBKU09OIG9iamVjdCIKfQo=" // dummy key

    connectToDatabase(key) // test fails here

    expect(admin.initializeApp).toHaveBeenCalledTimes(1)
    expect(admin.credential.cert).toHaveBeenCalledTimes(1)
    expect(admin.firestore()).toHaveBeenCalledTimes(1)
  })
})

这是我的相关(或可能相关)package.json(与 Yarn v1 一起安装):

{
  "dependencies": {
    "@firebase/app-types": "^0.6.0",
    "@types/node": "^13.13.5",
    "firebase-admin": "^8.12.0",
    "typescript": "^3.8.3"
  },
  "devDependencies": {
    "@types/jest": "^25.2.1",
    "expect-more-jest": "^4.0.2",
    "jest": "^25.5.4",
    "jest-chain": "^1.1.5",
    "jest-extended": "^0.11.5",
    "jest-junit": "^10.0.0",
    "ts-jest": "^25.5.0"
  }
}

我开玩笑的配置:

// /jest.config.js

module.exports = {
  setupFilesAfterEnv: ["jest-extended", "expect-more-jest", "jest-chain"],
  preset: "ts-jest",
  errorOnDeprecated: true,
  testEnvironment: "node",
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
  },
  moduleFileExtensions: ["ts", "js", "json"],
  testMatch: ["<rootDir>/tests/**/*.(test|spec).(ts|js)"],
  clearMocks: true,
}

标签: javascripttypescriptfirebasejestjsts-jest

解决方案


你的代码看起来不错。jest.mock模拟库的所有方法,默认情况下,所有方法都会undefined在调用时返回。

解释

您看到的问题与firebase-admin模块方法的定义方式有关。

firebase-admin包的源代码中,该initializeApp方法被定义为以下方法FirebaseNamespace.prototype

FirebaseNamespace.prototype.initializeApp = function (options, appName) {
    return this.INTERNAL.initializeApp(options, appName);
};

但是,该firestore方法被定义为一个属性:

Object.defineProperty(FirebaseNamespace.prototype, "firestore", {
    get: function () {
        [...]
        return fn;
    },
    enumerable: true,
    configurable: true
});

似乎jest.mock能够模拟直接在 中声明的方法prototype(这就是您的调用admin.initializeApp不会引发错误的原因),但不能模拟定义为属性的方法。

解决方案

为了克服这个问题,您可以在运行测试之前为该firestore属性添加一个模拟:

// /tests/lib/database.spec.ts
import * as admin from "firebase-admin"
import { connectToDatabase } from "@/lib/database"

jest.mock("firebase-admin")

describe("database connector", () => {
  beforeEach(() => {
    // Complete firebase-admin mocks
    admin.firestore = jest.fn()
  })

  it("should connect to Firebase when given valid credentials", () => {
    const key = "ewogICJkdW1teSI6ICJUaGlzIGlzIGp1c3QgYSBkdW1teSBKU09OIG9iamVjdCIKfQo=" // dummy key

    connectToDatabase(key) // test fails here

    expect(admin.initializeApp).toHaveBeenCalledTimes(1)
    expect(admin.credential.cert).toHaveBeenCalledTimes(1)
    expect(admin.firestore).toHaveBeenCalledTimes(1)
  })
})

替代解决方案

由于以前的解决方案不适合您,我会建议一个替代解决方案。firestore您可以定义属性以使其返回模拟函数,而不是分配方法的值。

为了简化模拟,我将mockFirestoreProperty在您的测试文件中创建一个小助手:

// /tests/lib/database.spec.ts
import * as admin from "firebase-admin"
import { connectToDatabase } from "@/lib/database"

jest.mock("firebase-admin")

describe("database connector", () => {
  // This is the helper. It creates a mock function and returns it
  // when the firestore property is accessed.
  const mockFirestoreProperty = admin => {
    const firestore = jest.fn();
    Object.defineProperty(admin, 'firestore', {
      get: jest.fn(() => firestore),
      configurable: true
    });
  };

  beforeEach(() => {
    // Complete firebase-admin mocks
    mockFirestoreProperty(admin);
  })

  it("should connect to Firebase when given valid credentials", () => {
    const key = "ewogICJkdW1teSI6ICJUaGlzIGlzIGp1c3QgYSBkdW1teSBKU09OIG9iamVjdCIKfQo=" // dummy key

    connectToDatabase(key) // test fails here

    expect(admin.initializeApp).toHaveBeenCalledTimes(1)
    expect(admin.credential.cert).toHaveBeenCalledTimes(1)
    expect(admin.firestore).toHaveBeenCalledTimes(1)
  })
})

推荐阅读