firebase 尝试使用jest初始化带有v9 firestore sdk的测试环境

7lrncoxx  于 2022-11-17  发布在  Jest
关注(0)|答案(2)|浏览(150)

我试图建立我的测试环境来测试我的安全fules与firestore。我已经复制了这个代码从https://firebase.google.com/docs/rules/unit-tests#before_you_run_the_emulator

let testEnv : RulesTestEnvironment;

beforeAll(async () => {

testEnv = await initializeTestEnvironment({
    projectId: "demo-project-1234",
    firestore: {
        rules: fs.readFileSync('firestore.rules', 'utf8'),
    },
});

});

然而,我得到这个错误。
The host and port of the firestore emulator must be specified. (You may wrap the test script with firebase emulators:exec './your-test-script' to enable automatic discovery, or specify manually via initializeTestEnvironment({firestore: {host, port}}).
有人知道怎么解决吗?

编辑

我尝试将主机和端口添加到正在运行的模拟器中,如下所示

let testEnv : RulesTestEnvironment;

beforeAll(async () => {

testEnv = await initializeTestEnvironment({
    projectId: "comment-section-e9c09",
    firestore: {
        rules: fs.readFileSync('firestore.rules', 'utf8'),
        host:'localhost',
        port:8080
    },
});

});

现在它似乎可以连接到我的模拟器,但当我尝试fx清除数据库时,如

test("sefse", () => {
    testEnv.clearDatabase()
})

我收到以下错误
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Error: The host and port of the database emulator must be specified. (You may wrap the test script with 'firebase emulators:exec './your-test-script'' to enable automatic discovery, or specify manually via initializeTestEnvironment({database: {host, port}}).".] {

bqucvtff

bqucvtff1#

我给予你一个“摩卡为主”的出发点:security.test.js:

import { readFileSync } from 'fs';
import { assertFails, assertSucceeds, initializeTestEnvironment } from "@firebase/rules-unit-testing";
import { doc, getDoc, setDoc } from "firebase/firestore";

let testEnv;
let unauthedDb;

describe("general database behaviour", () => {

before(async () => {
  testEnv = await initializeTestEnvironment({
    projectId: "demo-project-1234",
    firestore: {
      rules: readFileSync("firestore.rules", "utf8"),
      host: "127.0.0.1",
      port: "8080"
    },
  });
  unauthedDb = testEnv.unauthenticatedContext().firestore();
});

after(async () => {
  await testEnv.cleanup();
});

  it("should let read anyone the database", async () => {
    await testEnv.withSecurityRulesDisabled(async (context) => {
      await setDoc(doc(context.firestore(), 'data/foobar'), { foo: 'bar' });
    }); 
    await assertSucceeds(getDoc(doc(unauthedDb, 'data/foobar')))
  })
  it("should not allow writing the database", async () => {
    await assertFails(setDoc(doc(unauthedDb, '/data/foobar'), { something: "something" }))
  })
})
gg58donl

gg58donl2#

您是否在firebase.json文件中指定了firestore端口和规则路径?

"emulators": {
    "firestore": {
      "port": 8080
    }
  },
  "firestore": {
    "rules": "./rules/firestore.rules"
  }

相关问题