当我尝试访问正在运行的Firebase Emulator时,Jest测试挂起

u4vypkhs  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(65)

测试在这里-我目前正在为我的项目设置jest测试,所以这不是一个完整的测试。

import { expect, jest, describe, test, beforeAll, beforeEach, afterAll } from "@jest/globals";
import { firebaseDB, firebaseStorage } from "../firebaseprovider";
import { ref, set, get } from "firebase/database";

beforeAll(async () => {
    console.log("Running ArtworkProvider Tests");

    const fbRef = ref(firebaseDB, "test");
    const snapshot = await get(fbRef); // Hang occurs here
    console.log(snapshot.val())

})

字符串
https://github.com/jhengineerartist/art-website/blob/jest-test-add/src/lib/providers/test/artworkprovider.test.tsx
我得到的问题是beforeAll函数只是.挂起。我可以将超时延长到20秒,它只是挂起在await get(.)
我通过在终端执行以下操作,验证了我可以连接到用于数据库的端口

telnet localhost 9000

Trying 127.0.0.1...
Connected to localhost.


所以我不认为问题是端口无法访问。我也没有看到任何迹象表明设置函数被调用在模拟器日志。
我可以得到一些关于进一步故障排除的建议吗?或者根本原因是什么?这让我挠头,因为缺乏有用的日志和简单的挂起。
启动Firebase模拟器
已启动jest测试,并将NODE_ENV变量设置为测试。这将启用connectDatabaseEmulator和相关行为:

if (process.env.NODE_ENV === "test") {
    config.databaseURL = process.env.TEST_FIREBASE_DATABASEURL as string
    console.log(JSON.stringify(config));
}

const firebaseApp = initializeApp(config);
const firebaseDB = getDatabase(firebaseApp);
const firebaseStorage = getStorage(firebaseApp);

if (process.env.NODE_ENV === "test") {
    connectStorageEmulator(firebaseStorage, "localhost", 9199);
    connectDatabaseEmulator(firebaseDB, "localhost", 9000);
}


https://github.com/jhengineerartist/art-website/blob/jest-test-add/src/lib/providers/firebaseprovider.ts
尝试在我的模拟器中对实时数据库做一个简单的获取,但程序在等待获取(...)期间挂起。
我期待任何类型的响应-即使是失败也会让我更清楚地调试我的模拟器和测试配置的错误。

6za6bjd0

6za6bjd01#

我也遇到了同样的问题,我还不确定到底发生了什么,只知道它与使用 *jsdom测试环境 * 有关,但我确实设法解决了这个问题。
初始化firestore示例时,使用initializeFirestore()而不是getFirestore(),并确保传递useFetchStreams: false选项:

const testFirestore = initializeFirestore(testApp, {
  useFetchStreams: false,
})

字符串
注意:你可能会得到一个类型错误,因为属性不再公开。
useFetchStreams的默认值是true,因为firebase@v9,似乎jsdom环境不支持fetch readable streams。通过将其设置为false,firestore回退到使用XHR进行流数据。
以下是Firebase JS SDK存储库上的开放问题:https://github.com/firebase/firebase-js-sdk/issues/7808

相关问题