How do I mock getFirestore() in Jasmine test

Viewed 18

I'm getting the following error in my Jasmine unit test: FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app). error properties: Object({ code: 'app/no-app', customData: Object({ appName: '[DEFAULT]' }) }) FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

Here's my service:

import { Injectable } from '@angular/core';
import { getFirestore, getDoc } from 'firebase/firestore';
import { doc, DocumentData, DocumentSnapshot, setDoc } from '@angular/fire/firestore';
import { AlertController } from '@ionic/angular';
import { IUserInfo } from '../models/userInfo';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  db = getFirestore();

  constructor(private alertController: AlertController) { }

  saveProfile(uid: string, email: string, displayName: string): Promise<void> {
    return setDoc(doc(this.db, 'users', uid), {uid, email, displayName});
  }

  getProfile(uid: string): Promise<DocumentSnapshot<DocumentData>> {
    return getDoc(doc(this.db, `users`, uid))
  }

  saveUserOptions(userInfo: IUserInfo, uid: string): Promise<void> {
    return setDoc(doc(this.db, 'users', uid), {userInfo}, { merge: true });
  }

  async saved(message: any, header: string): Promise<void> {
    const alert = await this.alertController.create({
      subHeader: `${header}`,
      message: `${message}`,
      buttons: [
        {
          text: 'Ok',
          role: 'Ok',
          cssClass: 'secondary'
        }
      ]
    });

    await alert.present();
  }

  async getUserInfo(uid: string) {
    return (await this.getProfile(uid)).data();
  }
}

The test is simple:

import { TestBed } from '@angular/core/testing';

import { UserService } from './user.service';

describe('UserService', () => {
  let service: UserService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(UserService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

But I can't find anything online on how to mock the firebase services.

I created a test service to troubleshoot and figure out exactly which firebase import is causing the issue and it looks like once I add this line it throws the error: db = getFirestore();

Any help would be greatly appreciated

"jasmine-core": "~3.8.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~6.3.2",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-coverage-istanbul-reporter": "~3.0.2",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"@angular/fire": "^7.4.1",
0 Answers
Related