Search code examples
node.jsfirebasefirebase-securityfirebase-tools

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


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 ?


Solution

  • clearFirestoreData is now returned by the environment :

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

    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.

    If you're using this to run tests for testing the security rules, be sure to check the official documentation.