Search code examples
firebaseunit-testingfirebase-authenticationgoogle-cloud-functions

firebase-functions-test with authenticated account


I have some firebase functions that require the user to be logged in to call (e.g. you need to be logged in to see any data from the database):

const exampleEndpoint = onCall(async (request) => {
    if (!request.auth || !request.auth.uid) {
        throw new HttpsError(
            'unauthenticated',
            `You must be logged in to call the API`
        );
    }

    // rest of function ...
});

I'm using firebase-functions-test to do some unit tests, but can't find any documentation on how to test the functions as a logged in user. I've tried:

  • Logging in with signInWithEmailAndPassword() in the test context right before calling the wrapped function
  • Adding { auth: ... } to the wrapped function call with auth information
  • Logging all input data to the function
  • Reverting to a v1 function

How can I test my functions with an authenticated user, like how authentication information is passed in when you call the function normally from your front-end app?


Solution

  • After much searching, it appears like as of writing firebase-functions-test does not have support for this.

    However, you can simply call the functions like you normally would client-side. You can have a normal client app alongside your admin test configuration:

    const firebaseConfig = {
        // ...
    };
    const clientApp = initializeApp(firebaseConfig);
    const functions = getFunctions(clientApp);
    
    httpsCallable(functions, "functionName")(data);
    

    This is fine for onCall functions since you don't need admin-level access (e.g. for testing triggers directly), although you do need to always deploy your functions and logging won't be displayed in the test console