更新到@firebase/rules-unit-testing 2.0后,initializeAdminApp和clearFirestoreData方法不再可用

Agu*_*ana 10 node.js firebase firebase-security firebase-tools

我只是将我的依赖更新为"@firebase/rules-unit-testing": "^2.0.0"

它破坏了我的代码。我的代码是

import * as firebase from "@firebase/rules-unit-testing";

function getAdminFirestore() {
    return firebase.initializeAdminApp({ projectId: projectID }).firestore();
}

function getFirestore(auth?: TokenOptions) {
    return firebase.initializeTestApp({ projectId: projectID, auth: auth }).firestore();
}

beforeEach(async () => {
    await firebase.clearFirestoreData({ projectId: projectID });
});

after(async () => {
    await firebase.clearFirestoreData({ projectId: projectID });
});
Run Code Online (Sandbox Code Playgroud)

但我有很多错误,因为有些方法不再像这样可用

在此输入图像描述

那么 firebase/rules-unit-testing 2.0.0 中的等效方法是什么?

Seb*_* F. 8

clearFirestoreData现在由环境返回:

import * as fs from "fs";

const yourTestEnvinronmentConfiguration = {
    projectId: "yourProjectID",
    // ... your other specific environement test settings, see link below
};

const testEnv = await initializeTestEnvironment(yourTestEnvinronmentConfiguration);

await testEnv.clearFirestore();
Run Code Online (Sandbox Code Playgroud)

initializeAdminApp有点棘手。实现这一目标的一种方法似乎是:

// v8
testEnv.withSecurityRulesDisabled(async (context) => {
    await context.firestore().collection("foo").doc("bar").set({});
});

// V9
testEnv.withSecurityRulesDisabled(async (context) => {
    const adminFs = context.firestore();
    const foo = collection(adminFs, "foo");
    const bar = doc(foo , "bar");
    await setDoc(bar , {});
});
Run Code Online (Sandbox Code Playgroud)

测试两者(使用 v9 项目)可以确认它的工作原理。

另请注意,您将无法像以前一样工作。如果您尝试,您可能会遇到一条错误消息:

错误:此 RulesTestContext 不再有效。使用 withSecurityRulesDisabled 时,请确保在回调函数中对上下文执行所有操作,并返回一个在操作完成时解析的 Promise。

我最终放弃了我为获得“admin firestore”而制作的助手,因为总而言之,它让我只获得了一行。

如果您使用它来运行测试来测试安全规则,请务必查看官方文档