【发布时间】:2020-08-24 11:07:21
【问题描述】:
我有一个函数来处理通过 Admin SDK 连接到 Cloud Firestore。我知道该功能工作正常,因为应用程序连接并允许写入数据库。
现在我正在尝试用 Jest 测试这个功能。为避免在此功能范围之外进行测试,我正在模拟 firebase-admin 节点模块。但是,我的测试失败并出现错误“TypeError: admin.firestore is not a function”。
我的函数和测试都是用 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,
}
【问题讨论】:
标签: javascript typescript firebase jestjs ts-jest