【发布时间】:2018-03-15 18:57:01
【问题描述】:
有没有办法在本地运行 firestore(例如用于测试目的)?
针对数据库编写测试的方法是什么(使用模拟除外)
【问题讨论】:
标签: database firebase testing google-cloud-firestore
有没有办法在本地运行 firestore(例如用于测试目的)?
针对数据库编写测试的方法是什么(使用模拟除外)
【问题讨论】:
标签: database firebase testing google-cloud-firestore
现在还有一个Firebase Emulator Suite。
本地模拟(至少出于测试 Firestore 规则的目的)已使用 @firestore/testing 演示 at Firebase Summit 2018 并记录在 Test your Cloud Firestore Security Rules 下。
看起来是这样的:
const firebase = require(`@firebase/testing`)
const app = firebase.initializeTestApp({
projectId: 'my-project',
auth: { uid: '123', email: 'name@domain.com' }
})
const attempt = app.firestore()
.collection('colId').doc('docId').get()
firebase.assertFails(attempt)
firebase.assertSucceeds(attempt)
这似乎是早期的,因为它没有在发行说明中注明,但我确信它会出现。
【讨论】:
目前还没有,但请继续关注,因为这是我们想要提供的东西。
同时,我们建议使用单独的测试项目来解决这个问题。每个项目的每日免费套餐对此也有帮助。
【讨论】:
您可以通过运行以下命令来运行 Firestore 模拟器:
gcloud beta emulators firestore start
然后根据控制台输出设置FIRESTORE_EMULATOR_HOST 环境变量(例如运行export FIRESTORE_EMULATOR_HOST=::1:8505)。
这需要在您的系统路径上安装 Google Cloud SDK 和 Java 8+ JRE。
【讨论】:
gcloud beta emulators firestore start --host-port localhost:8080 这样的固定端口时,它确实对我有用
为 firestore 测试编写一个 js 示例 test.js 您可以使用此格式示例测试写入
var data = {
value: {createTime: new Date(),
updateTime: new Date(),
fields:{
name:{stringValue:'new value data'},
age:{integerValue:50}
}
},
oldValue: {createTime: new Date(), //old create time
updateTime: new Date(), //old update time time
fields:{
name:{stringValue:'olvalue data'},
age:{integerValue:50}
}
}
};
testFireStoreEvent(data);
为了运行执行
firebase experimental:functions:shell < test.js
更新!!!!适用于写入和更新事件
var data = {
before: {
//your before data
},
after: {
//your after data
}
};
testFireStoreEvent(data);
【讨论】:
有两个库试图促进对 firebase sdk 的模拟。
1) https://github.com/soumak77/firebase-mock
2)https://github.com/mikkopaderes/mock-cloud-firestore
我目前使用第一个,因为它似乎实现了更多的 SDK。
它们并不完美,但它们目前足以满足我的需求,并且比其他方法更可取,因为它们完全在进行中。
请注意,如果从 Webpack/web 代码中按原样使用 firebase-mock (#1) 确实会导致 webpack 错误。要解决此问题,您可以使用选项 #2 (mock-cloud-firestore),或使用此处提到的解决方法(直到合并修复程序):https://github.com/soumak77/firebase-mock/issues/157#issuecomment-545387665
3) Firestore emulator:需要 google-cloud-sdk,并且依赖于单独的进程
4) 单独的测试项目:依赖于互联网的连接,这也意味着可能的配额限制/成本
5)firebase-server:只支持realtime-database api,不支持Firestore
【讨论】:
可以使用 gcloud 在本地设置 Firestore。
运行 gcloud beta emulators firestore start --host-port=localhost:8081 启动 firestore 模拟器,如果启动成功,您将看到 Dev App Server is now running
如果您使用的是@google-cloud/firestore,请以这种方式创建 Firestore 实例
// Firestore instance only for test env
const { Firestore } = require('@google-cloud/firestore')
const instance = new Firestore({ projectId; 'Your project id', host: 'localhost', 'port': 8081})
【讨论】:
现在您可以选择通过设置本地主机来使用本地 Firestore 模拟器:
var db = firebaseApp.firestore();
if (location.hostname === "localhost") {
db.settings({
host: "localhost:8080",
ssl: false
});
}
【讨论】: