Jest/Typescript 测试 Firebase/Firestore Admin SDK 的最佳实践

XBu*_*123 6 firebase typescript jestjs google-cloud-firestore firebase-cli

我正在编写一个应用程序,其后端编写为节点/express 服务器,通过 firebase 功能上的 Admin SDK 运行 firestore 命令。我想知道测试数据库功能的最佳方法是什么。此类函数的示例如下:

export const deleteDocument = async(id: string): Promise<void> => {
    try {
        await firestore.collection("sampleCollection").doc(id).delete();
    } catch (e) {
        throw new Error(`Could not delete ${id}`);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我想运行一个像这样的单元测试(我知道这里的实际逻辑有点奇怪,但它是即时完成的,并不是问题的重点):

it('should delete a document from the sample collection', async () => {
    //This would already be tested
    const id = await createDocument(...);
    if (id !== undefined) {
      await deleteDocument(id);
      try {
        await getCollective(id);
        expect(true).toBe(false);
      } catch (e) {
        expect(true).toBe(true);
      }
    } else {
      expect(id).toBeDefined();
    }
});
Run Code Online (Sandbox Code Playgroud)

firestore这样定义我的实例:

import * as admin from 'firebase-admin';
const firebase = admin.initializeApp({credential: admin.credential.cert(...), ...otherConfig});
const firestore = firebase.firestore();
export {firebase, firestore};
Run Code Online (Sandbox Code Playgroud)

然后,这将导致具有管理员权限的初始化 Firebase 应用程序。然后我运行firebase emulator:start --only firestore,functions,这会在模拟器上启动后端。我现在可以在我在 Express 服务器上创建的端点上运行 '/delete/:id',该端点运行 function deleteDocument。当我通过触发该功能“手动”执行此操作时,效果非常好。问题是当我想运行测试时。FIREBASE_EMULATOR_PORT由于某种原因,即使环境变量已设置为正确的值,测试本身也不会连接到模拟器。

我确实尝试使用 的@firebase/testing.initializeAdminApp() 方法,但是此方法的 firestore 类型与admin.initializeApp()from的 firestore 类型崩溃firestore-admin,这使得我无法使用测试中的函数切换数据库,如下所示。我还希望避免模拟这些函数,而是使用模拟器来发挥它的价值。

所以我的问题是我真的不知道如何运行测试。如果我在运行模拟器时执行此操作,则测试会从我的生产 Firestore(而不是模拟器)获取数据,即使函数上的 Express 服务器将数据正确加载到 Firestore 模拟器也是如此。

感谢您的帮助,如果您需要更多信息,我将很乐意提供。