使用不带身份验证的admin SDK针对本地Firestore模拟器编写测试

时间:2020-09-03 22:00:11

标签: firebase google-cloud-firestore

编辑:本质上是firebase-emulator文档的问题。参见讨论here


我正在尝试使用nodejs admin SDK直接访问在本地模拟器上运行的Firestore实例。最小示例:

// test.js
const admin = require("firebase-admin"); // version 9.1.1
admin.firestore().collection('foo').add({ a: 1 });

然后仅$ node test.js看看是否有效。

与此相关的唯一文档是one sentence,它告诉我设置一个环境变量,所以我做了,就像这样:

$ FIRESTORE_EMULATOR_HOST='localhost:1003' node test.js

但是我收到一条错误消息Unable to detect a Project Id in the current environment.,但是我在文件项目文件夹中 am 。我想念什么?我最终的目标是编写单元测试来测试使用Firestore的服务器代码。该服务器运行在云功能上,目前,我能够从测试套件中触发该功能,该套件可以成功读取/写入本地数据库,但是对于编写测试来说太费时了。

firebase.json:

{
  ...
  "emulators": {
    "ui": {
      "enabled": true,
      "port": 1000
    },
    "hosting": {
      "port": 1001
    },
    "functions": {
      "port": 1002
    },
    "firestore": {
      "port": 1003
    }
  }
}

(我已经尝试了这4个端口中的每个端口,但均无作用)

3 个答案:

答案 0 :(得分:0)

使用命令firebase emulators:start运行仿真器时,您将获得仿真功能的端口,例如:

 ───────────────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! View status and logs at http://localhost:4000 │
└───────────────────────────────────────────────────────────────────────┘
┌───────────┬────────────────┬─────────────────────────────────┐
│ Emulator  │ Host:Port      │ View in Emulator UI             │
├───────────┼────────────────┼─────────────────────────────────┤
│ Functions │ localhost:5001 │ http://localhost:4000/functions │
├───────────┼────────────────┼─────────────────────────────────┤
│ Firestore │ localhost:3000 │ http://localhost:4000/firestore │
└───────────┴────────────────┴─────────────────────────────────┘
  Other reserved ports: 4400, 4500
Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.

比起使用我创建的最小示例的链接:

const admin = require("firebase-admin"); // version 9.1.1
admin.initializeApp();
var db = admin.firestore();
db.settings({
    host: "localhost:3000",
    ssl: false
});
admin.firestore().collection('foo').add({ a: 1 })
.then( (r) => console.log("document added: ",r.path) )
.catch( (e) => console.log("error: ",e) );

请注意,必须使用initializeApp方法创建第一个应用程序实例,然后才能设置模拟器的路径。但是我想还有很多其他方法可以做到这一点。如果成功,这将显示创建文档的路径。我没有使用任何其他设置。

答案 1 :(得分:0)

我的经验是 Firebase 模拟器喜欢被赋予一个虚拟项目 ID。我在我的项目中使用了 bunny 之类的东西,让它看起来很有趣。

启动模拟器:

$ firebase emulators:start --project=bunny --only auth,functions,firestore

不过,实际情况要复杂得多。对于真实世界的示例,您可以查看 http://github.com/akauppi/GroundLevel-firebase-es

答案 2 :(得分:0)

实际上,我同意@akauppi 的answer。这是来自 firebase 模拟器文档的片段:

<块引用>

连接到身份验证模拟器时,您需要指定项目 ID。您可以直接将项目 ID 传递给 initializeApp 或设置 GCLOUD_PROJECT 环境变量。请注意,您不需要使用真实的 Firebase 项目 ID;身份验证模拟器将接受任何项目 ID。