initializeAdminApp and clearFirestoreData method no longer available after update to @firebase/rules-unit-testing 2.0

Viewed 271

I just update my dependency to "@firebase/rules-unit-testing": "^2.0.0"

and it breaks my code. my code was

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 });
});

but I have a lot of errors because some methods no longer available like this

enter image description here

so what is the equivalent method in firebase/rules-unit-testing 2.0.0 ?

1 Answers

clearFirestoreData is now returned by the environment :

import * as fs from "fs";

const testEnv = await initializeTestEnvironment({
    projectId: "yourProjectID",
    firestore: {
        rules: fs.readFileSync("firestore.rules", "utf8"),
    },
});

await testEnv.clearFirestore();

initializeAdminApp is a bit more tricky. It seems that one way to achieve it would be :

// 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 , {});
});

Tested both (with a v9 project) can confirm it works.

Also note that you won't be able to work like you did previously. If you try, you will probably encounter an error message saying :

Error: This RulesTestContext is no longer valid. When using withSecurityRulesDisabled, make sure to perform all operations on the context within the callback function and return a Promise that resolves when the operations are done.

I ended ditching the helper I made to get that "admin firestore" because all in all, it made me just gain one line.

for more info from official documentation: https://firebase.google.com/docs/firestore/security/test-rules-emulator#run_local_unit_tests

Related