Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a firebase functions from a unit test using Firebase Emulators?

I have the firebase emulators running.

My application can call a firebase cloud function that can create a custom user claim if the user is allowed to (depending on a value in the database)

I'm trying to invoke that function:


import * as firebase from '@firebase/testing';
import * as fs from 'fs';

const app = firebase.initializeTestApp({
  databaseName: 'mydb',
  auth: {
    uid: 'useruid'
  },
});

describe('Firebase Functions', () => {
  beforeEach(async () => {
    await firebase.loadDatabaseRules({
      databaseName: 'mydb',
      rules: fs.readFileSync('database.rules.json', 'utf8'),
    });
  });

  afterAll(async () => {
    await Promise.all(firebase.apps().map((app) => app.delete()));
  });

  const cloudfunction = app.functions().httpsCallable('cloudfunction')

  it('throws error if user is not authenticated', async () => {
    await firebase.assertFail(cloudfunction())
  })
});


This is throwing an error:

Error: Error: Response for preflight has invalid HTTP status code 404

like image 244
Simon Tran Avatar asked Sep 15 '21 00:09

Simon Tran


People also ask

How do you test Firebase authentication?

Firebase Authentication, for example, allows authentication via phone number. We enter a phone number, get a verification code via SMS, enter the verification code and are authenticated. Let's say we want to find the uid of a user by phone number in one of our services for some reason. We can use Firebase Auth.

How do I test Firebase integration?

On the Firebase console navigation bar, click Test Lab, and then click Get Started -> Run a Robo test. Click Browse, browse to your app APK, and then click Continue. Define your test matrix by selecting which devices, Android API levels, screen orientations and locales you want to test your app against.


1 Answers

In my opinion, you don't need to call firebase from your unit test, because it is not your business is firebase working correctly or not, you need to test your business logic so that means that you will mock the method which calls to the firebase and test expectable returning values of this method, for example, you can write 2 cases when notification will be sent without error and second if firebase service will return failure, for those 2 cases your code should have appropriate behavior. Testing firebase service will be done by the team working on the firebase

like image 173
Armen Grigoryan Avatar answered Sep 18 '22 15:09

Armen Grigoryan