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

问题描述

我正在编写一个应用程序,后端通过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}`);
    }
}

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

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();
    }
});

我这样定义我的firestore实例:

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

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

我确实尝试过使用@firebase/testing的.initializeAdminApp()方法,但是此方法中的Firestore类型与admin.initializeApp()中的firestore-admin的Firestore类型一起崩溃,因此看起来就像我无法使用测试中的函数切换数据库一样,如here所示。我也希望避免模拟功能,而是使用模拟器来实现其价值。

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

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)