4

I am trying to test a firebase app locally.

I am running the test with firebase emulators:exec --only firestore 'mocha -r ts-node/register src/**/*.spec.ts

In my spec, I import @firebase/testing and setup my app and followed the directions from https://firebase.google.com/docs/rules/unit-tests

I have a FirebaseService which is a singleton wrapper for my methods into which I inject my firebase app. In production, I'll inject the firebase, and it gets initialized in the FirebaseService in testing, I initialize outside of the service.

The wrapper is fairly simple


export const FirebaseService = (function(): FirebaseSrvc {
  let firebase;
  const fbServiceObj: FirebaseSrvc = {
    getInstance: (firebaseConfig, firebaseCore, initialize) => {
      firebase = firebaseCore;
      if (initialize && firebase.apps.length === 0) {
        firebase.initializeApp(firebaseConfig);
      }

      return fbServiceObj;
    },


    createActivity: async (title: string) => {
      try {
        const firebaseUid = firebase.auth().currentuser.uid;
        const newActivity: ActivityProps = {
          title,
          created_at: 123445,
          created_by: firebaseUid,
          public: false,
          available_to: [firebaseUid],
        };
        console.log(' before create', newActivity);
        const createResponse = await firebase
          .firestore()
          .collection('activities')
          .doc(stringToSafeId(title))
          .set(newActivity);
        console.log('create response', createResponse);
        return true;
      } catch (e) {
        console.log('error creating activity', e);
      }
    },

    getActivity: async (title: string): Promise<ActivityProps> => {
      try {
        const actResponse: DocumentReferenceTo<ActivityProps> = await firebase
          .firestore()
          .collection('activities')
          .doc(stringToSafeId(title))
          .get();
        return actResponse as ActivityProps;
      } catch (e) {
        console.log('error getting activity from firebase', e);
      }
    },
  };

  return fbServiceObj;
})();

The test I am attempting to run is

import * as firebase from '@firebase/testing';
import { assert } from 'chai';
import 'mocha';
import * as appConfig from '../../app-dev.json';
import { FirebaseService } from '../services/FirebaseService';

firebase.initializeTestApp({ ...appConfig.expo.extra.firebase, auth: { uid: 'random', email: 'test@test.com' } });


describe('Activity', async () => {
  const fb = FirebaseService.getInstance(appConfig.expo.extra.firebase, testApp, false);
  const activityData = new Activity(fb);
  beforeEach(async () => await firebase.clearFirestoreData({ projectId }));

  it('should create a new activity', async () => {
    await activityData.set('test-activity'); // this runs FirebaseService.createActivity
    const findActivity = await activityData.get('test-activity'); // this run FirebaseService.getActivity
    assert(findActivity.title === 'test-activity');
  });
});

When I run the test I get an error

Your API key is invalid, please check you have copied it correctly.] {
  code: 'auth/invalid-api-key',
  message: 'Your API key is invalid, please check you have copied it correctly.'
}

I can confirm that the API key which is passed into firebase.initializeTestApp matches the Web API Key in my firebase console.

I have also downloaded the google-services.json from my firebase console and lists

{
 "api_key": [
  { "current_key": different_from_web_key}
  ]
}

And I have replaced my existing key with this new key, I still get the same error. I have also tried setting up initializeTestApp({ projectId }) which is how the example from firebase docs sets it up, and I receive the same result.

I am using the same project details to run a project locally in android studio, and I am able to authenticate and write to firestore, so the API key I am using does work, but it appears to have issues being used in the test app.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
pedalpete
  • 21,076
  • 45
  • 128
  • 239

1 Answers1

-2

This usually doesn't have a specific way to solve it. It might be that even a new copy and paste of the API key to the parameters, might make it work and the error to disappear.

I would recommend you to take a look at the following posts from the Community, that have some possible fixes for the error that you are facing.

In addition to that, since Firebase has free support offers, I think you reaching out to the Firebase support would help you fix this quickly. You should be able to contact directly for free.

Let me know if the information helped you!

gso_gabriel
  • 4,199
  • 1
  • 10
  • 22
  • 1
    All the links point to mistakes using regular Firebases's `initializeApp`. The problem here is when using `initializeTestApp` from `@firebase/testing`. In this scenario I can't understand why the API key could be a problem. Also, the API doesn't even receive an API key. – joaomilho Dec 28 '20 at 14:18