gpt4 book ai didi

javascript - 如何从客户端使用 firestore 模拟器

转载 作者:行者123 更新时间:2023-11-29 10:26:37 25 4
gpt4 key购买 nike

我想在本地测试我的 firebase 函数。这些函数进行 firestore 查询。

所以我启动模拟器 firebase emulators:start 并在我的客户端中使用 firebase.functions().useFunctionsEmulator('http://localhost:5001') .

当我在我的客户中调用它们时,我的函数运行良好。我可以在 firestore 模拟器中读取/写入数据。

问题:

我想直接在我的客户端中读取 firestore 模拟器数据,例如:

firebase.firestore().collection('tests').get().then(tests => {
console.log( tests.docs.map(test=>test.map) )
})

但我找不到如何在我的客户端中设置 firestore 模拟器。

这里是我尝试过的:

1) Firestore 设置

firebase.firestore().settings({
host:'http://localhost:8080',
ssl:false
})

结果:

我得到 @firebase/firestore: Firestore (6.3.5): 无法到达 Cloud Firestore 后端。后端在 10 秒内没有响应。 在我的客户端控制台中。

http 请求返回'未找到'

2) 在我的 firebaseConfig 中设置模拟器 url

var firebaseConfig = {
// ...
databaseURL: "http://localhost:8080",
// ...
}

firebase.initializeApp(firebaseConfig)

在这种情况下,请求远程服务器 ( https://firestore.googleapis.com. .)。

所以我想设置这两种情况之一:

1) 在我的函数模拟器中使用远程 firestore

2) 在我的客户端代码中使用本地 firestore 模拟器。

有人做过吗?

最佳答案

安装测试库

npm i -D @firebase/testing

在另一个终端中设置并启动模拟器:

firebase setup:emulators:firestore

firebase serve --only firestore

设置测试

const firebase = require("@firebase/testing");

// Helper function to setup test db
function authedApp(auth) {
return firebase
.initializeTestApp({ projectId: FIRESTORE_PROJECT_ID, auth })
.firestore();
}

// Setup methods
beforeEach(async () => {
// Clear the database between tests
await firebase.clearFirestoreData({ projectId: FIRESTORE_PROJECT_ID });
});

// Clean up apps between tests.
afterEach(async () => {
await Promise.all(firebase.apps().map(app => app.delete()));
});

运行测试

it("should retrieve correct item", async () => {
// Init test db
const db = authedApp(null);

// Manually add item to collection
const ref = await db.collection(COLLECTION_NAME).add({name: 'test item'});

// Fetch item by id
const resp = await db.collection(COLLECTION_NAME).doc(ref.id).get();

// test the output
expect(resp).toBeDefined();
expect(resp).toEqual(expect.objectContaining({name: 'test item'}));
});

当然,您的特定设置和环境会有所不同,但这至少应该给您一个大概的想法。更多信息:https://firebase.google.com/docs/rules/unit-tests

注释来自 ' Test your Cloud Firestore Security Rules '

Data written to the Cloud Firestore emulator is held in memory until the emulator is stopped. If the emulator is run continuously, this may have an impact on test isolation. To ensure that data written in one test is not read in another, either explicitly clear your data with clearFirestoreData, or assign a different project ID for each independent test: when you call firebase.initializeAdminApp or firebase.initializeTestApp, append a user ID, timestamp, or random integer to the projectID.

编辑:我写了一个 blog post前一段时间,其中详细介绍了该主题。

关于javascript - 如何从客户端使用 firestore 模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57537017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com