javascript - 在 Jest : "TypeError: admin.firestore is not a function" 中模拟 Firebase 管理员时出错

标签 javascript typescript firebase jestjs ts-jest

我有一个函数来处理通过 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 配置:

// /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,
}

最佳答案

你的代码看起来不错。 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)
  })
})

关于javascript - 在 Jest : "TypeError: admin.firestore is not a function" 中模拟 Firebase 管理员时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61686830/

相关文章:

javascript - 如何在 Nextjs 中处理创建/编辑页面,我应该在 ServerSideProps 中还是在组件中获取产品

firebase - 如何为 Cloud Functions for Firebase 设置本地环境变量

ios - 尝试Pod安装Firebase时出现Cocoapods错误-Nanaimo

javascript - 要求 js 文件不会执行

javascript - 运行 js 函数 onchange()

javascript - JS - 强制打印死键

java - 如何从 Firestore Android 中的集合中获取文档列表

php - 在没有明显重新加载的情况下更新 URL

javascript - 如何在元素悬停时将样式应用于多个类?

javascript - 如何从 url 替换键和参数的值?