Skip to content

Latest commit

 

History

History
510 lines (346 loc) · 26.4 KB

testing.md

File metadata and controls

510 lines (346 loc) · 26.4 KB
AngularFire ❱ Developer Guide ❱ Testing

Testing

This page shows how to unit test components and services that use AngularFire. It covers Vitest, which the Angular CLI sets up for new projects, Jest, and Karma with Jasmine.

Each pattern says whether it applies to the modular API (@angular/fire/auth and the other product entry points), the compat API (@angular/fire/compat), or both.

Contents

Choose a test runner

Vitest is what ng new sets up. AngularFire needs no extra test configuration there. If a spec file mocks a module, one Angular CLI setting matters: see Turn on test isolation.

Jest works too. Jest 30 needs one addition to its configuration before a test can import firebase/auth. See Jest setup.

Karma with Jasmine is what ng new set up before Angular 21. AngularFire needs no extra test configuration there. Jasmine has no module mock, and every spec file runs in the same browser page. See Karma and Jasmine setup.

The examples below test this component:

// user-badge.ts
import { Component, inject } from '@angular/core';
import { Auth, authState } from '@angular/fire/auth';

@Component({ selector: 'app-user-badge', template: '' })
export class UserBadge {
  private readonly auth = inject(Auth);
  readonly user$ = authState(this.auth);
}

Decide how much of Firebase the test runs

Approach Use it when
Real services with made-up options The code only needs the services to exist: it injects them, builds references, or reads the signed-out state.
Replace AngularFire in the test The test needs a specific user or specific data.
The Firebase Local Emulator Suite The test needs a real backend. See the emulator sections in Authentication and Realtime Database.

Use real services with made-up options

Applies to the modular API.

Provide AngularFire the way the app does, with an options object that belongs to no real project:

import { TestBed } from '@angular/core/testing';
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
import { getAuth, provideAuth } from '@angular/fire/auth';
import { firstValueFrom } from 'rxjs';
import { UserBadge } from './user-badge';

const fakeOptions = { apiKey: 'fake-api-key', projectId: 'demo-project' };

describe('UserBadge', () => {
  it('starts signed out', async () => {
    TestBed.configureTestingModule({
      providers: [provideFirebaseApp(() => initializeApp(fakeOptions)), provideAuth(() => getAuth())],
    });
    const component = TestBed.createComponent(UserBadge).componentInstance;

    expect(await firstValueFrom(component.user$)).toBeNull();
  });
});

The Firebase SDK does not contact Google to create an app, an Auth instance, or a Firestore reference, so this test needs no network. authState emits null. With provideFirestore(() => getFirestore()), the value of collection(firestore, 'todos').path is 'todos'.

Each product reads its own part of the options. Auth needs apiKey and Firestore needs projectId. Storage also needs storageBucket. Without it, building a Storage reference throws No default bucket found.

Limitations

There is no backend

A call that needs one fails. signInWithEmailAndPassword rejects with auth/api-key-not-valid.-please-pass-a-valid-api-key. under Vitest, where the request reaches Google, and with auth/network-request-failed under Jest. Use the emulator or replace AngularFire for those tests.

The app outlives the test

TestBed resets between tests, but the Firebase app stays registered. Under Vitest it can still be registered when a different spec file starts, unless test isolation is on. Under Karma the app is always still registered. See Every spec file shares one page.

Using the same options again is fine. Using different options in a later test throws Firebase App named '[DEFAULT]' already exists with different options.

So use one set of options in every spec file. If you need more than one, every spec file that creates an app has to delete it after each test:

import { TestBed } from '@angular/core/testing';
import { deleteApp, getApps } from '@angular/fire/app';

afterEach(async () => {
  await TestBed.runInInjectionContext(() => Promise.all(getApps().map(app => deleteApp(app))));
  TestBed.resetTestingModule();
});

TestBed.runInInjectionContext is there because a test hook runs outside an injection context, where AngularFire's functions print the warning described in Zones. That call creates the test module, and under Jest this hook runs after Angular's own reset, so TestBed.resetTestingModule() resets it again for the next test.

The hook is for apps created through the modular API. It also deletes an app created with AngularFireModule.initializeApp, and the next test that calls AngularFireModule.initializeApp then fails with Firebase App named '[DEFAULT]' already deleted, even when its options are the same.

Replace AngularFire in the test

Mock the module

Applies to the modular API.

The component imports Auth and authState from @angular/fire/auth. The test replaces the module with its own version of those two names.

Vitest example

import { TestBed } from '@angular/core/testing';
import { Auth, authState } from '@angular/fire/auth';
import { firstValueFrom, of } from 'rxjs';
import { UserBadge } from './user-badge';

vi.mock('@angular/fire/auth', () => ({
  Auth: class {},
  authState: vi.fn(() => of({ uid: 'user-1' })),
}));

describe('UserBadge', () => {
  it('shows the signed-in user', () => {
    TestBed.configureTestingModule({ providers: [{ provide: Auth, useValue: {} }] });
    const component = TestBed.createComponent(UserBadge).componentInstance;

    return firstValueFrom(component.user$).then(user => expect(user).toEqual({ uid: 'user-1' }));
  });

  it('handles a signed-out visitor', () => {
    vi.mocked(authState).mockReturnValueOnce(of(null));
    TestBed.configureTestingModule({ providers: [{ provide: Auth, useValue: {} }] });
    const component = TestBed.createComponent(UserBadge).componentInstance;

    return firstValueFrom(component.user$).then(user => expect(user).toBeNull());
  });
});

The mock lists every name the code under test imports from the module. If one is missing, Vitest says which: No "Auth" export is defined on the "@angular/fire/auth" mock.

Auth only has to be a class, so that TestBed can use it as a provider token. It is provided as an empty object because the mocked authState never reads it. mockReturnValueOnce changes the value for one test, and the next test gets the default again.

Keep async out of the spec file

The tests return a promise and use no async or await. That is deliberate. In an Angular 22 app that uses zone.js, a spec file that calls vi.mock fails to load if it also contains an async function. See vi.mock in an Angular 22 app that uses zone.js.

Turn on test isolation

Turn on test isolation when any spec file calls vi.mock. The Angular CLI runs spec files in shared workers, so a mock set in one file can replace the module in another file that never asked for it, and which files fail changes from run to run. The usual sign is NG0201: No provider found for `Auth` in a test that does provide Auth.

With @angular/build 22, set isolate on the test target in angular.json:

"test": {
  "builder": "@angular/build:unit-test",
  "options": { "isolate": true }
}

@angular/build 21 has no isolate option. There, set "runnerConfig": true in the same place and add a vitest-base.config.ts next to angular.json:

import { defineConfig } from 'vitest/config';

export default defineConfig({ test: { isolate: true } });

With isolation on, every spec file loads its imports again, so the run takes longer.

Mock the package, not your own files

Angular's Vitest setup rejects vi.mock('./user-badge') with the error: The "vi.mock" and related methods are not supported for relative imports with the Angular unit-test system. Replace your own services through TestBed providers.

Jest example

Write jest in place of vi. The tests stay as they are in the Vitest example.

jest.mock('@angular/fire/auth', () => ({
  Auth: class {},
  authState: jest.fn(() => of({ uid: 'user-1' })),
}));

Jest needs none of the three Vitest notes above: it keeps spec files apart, accepts async tests, and can mock a relative import.

Give Auth a fake object

Applies to the modular API.

The functions that read the signed-in state work with a small object in place of Auth. No module mock is needed.

import { TestBed } from '@angular/core/testing';
import { Auth } from '@angular/fire/auth';
import { firstValueFrom } from 'rxjs';
import { UserBadge } from './user-badge';

const fakeUser = { uid: 'user-1', getIdToken: () => Promise.resolve('token-1') };

const fakeAuth = {
  onAuthStateChanged: (next: (value: unknown) => void) => {
    next(fakeUser);
    return () => undefined;
  },
  onIdTokenChanged: (next: (value: unknown) => void) => {
    next(fakeUser);
    return () => undefined;
  },
  signOut: () => Promise.resolve(),
};

it('shows the signed-in user', async () => {
  TestBed.configureTestingModule({ providers: [{ provide: Auth, useValue: fakeAuth }] });
  const component = TestBed.createComponent(UserBadge).componentInstance;

  expect(await firstValueFrom(component.user$)).toEqual(fakeUser);
});

Under Jasmine the last line of this test needs one change. See The fake Auth example needs one change.

This object is enough for authState, user, idToken and signOut. authState calls onAuthStateChanged. user and idToken call onIdTokenChanged, and idToken also calls getIdToken on the user. Leave out the members the code under test does not use.

It is not enough for signInWithEmailAndPassword, which throws authInstance._getRecaptchaConfig is not a function. Mock the module for sign-in calls.

Replace a compat service

Applies to the compat API.

Compat services are classes with methods and properties, so TestBed can replace one with an object:

import { TestBed } from '@angular/core/testing';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { of } from 'rxjs';

TestBed.configureTestingModule({
  providers: [{ provide: AngularFireAuth, useValue: { authState: of({ uid: 'user-1' }) } }],
});

A component that injects AngularFireAuth then reads { uid: 'user-1' } from authState.

What does not work

Spying on AngularFire functions

Applies to the modular API.

vi.spyOn(fireAuth, 'authState') throws Cannot spy on export "authState". Module namespace is not configurable in ESM. In Jest, jest.spyOn(fireAuth, 'authState') throws Cannot redefine property: authState. Jest throws the same error for functions imported from firebase/auth directly, so this is not specific to AngularFire.

Do this instead: mock the module. Jasmine's spyOn fails too and Jasmine has no module mock. See Jasmine has no module mock.

A Jest suite that already relies on jest.spyOn can keep it by mocking the module with a copy of itself first. __esModule: true is needed when esModuleInterop is on in the TypeScript configuration. Without it jest.spyOn still throws there.

import * as fireAuth from '@angular/fire/auth';
import { of } from 'rxjs';

jest.mock('@angular/fire/auth', () => ({ __esModule: true, ...jest.requireActual('@angular/fire/auth') }));

it('shows the signed-out state', () => {
  const spy = jest.spyOn(fireAuth, 'authState').mockReturnValue(of(null));
  // ...
});

Fake Firestore and Storage objects

Applies to the modular API.

Unlike Auth, these cannot be replaced with a plain object. collection(fakeFirestore, 'items') throws Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore. ref(fakeStorage, 'file.txt') throws Cannot read properties of undefined (reading 'path').

Do this instead: use real services with made-up options when the code only builds references, and mock the module when it reads data.

No Firebase App has been created

Applies to the modular API.

The full message is Firebase: No Firebase App '[DEFAULT]' has been created - call initializeApp() first (app/no-app). Something asked for the default Firebase app and none exists. In a test this has three causes:

  • The code under test calls getAuth(), getFirestore() or a similar function itself. Adding provideFirebaseApp to the test is not enough, because it creates the app only when something injects FirebaseApp or a service that depends on it, such as Auth. Do one of these:
    • Create the app before creating the component, with TestBed.runInInjectionContext(() => initializeApp(fakeOptions)). Configure TestBed first, because it cannot be configured after this call.
    • Change the code to inject Auth or Firestore.
  • The test imports FirebaseAppModule without providing an app. Add provideFirebaseApp(() => initializeApp(fakeOptions)).
  • The app was given a name. initializeApp(fakeOptions, 'name') does not create the default app, so provideAuth(() => getAuth()) cannot find one. Drop the name.

A test that provides nothing at all fails differently, with Angular's NG0201: No provider found for `Auth`. Add provideFirebaseApp and provideAuth, or one of the replacements above.

The compat AngularFireAuth with a real app

Applies to the compat API.

AngularFireModule.initializeApp(fakeOptions) with the real AngularFireAuth does not run under Vitest. Reading authState throws INTERNAL ASSERTION FAILED: Expected a class definition from the Firebase SDK. Under Jest it runs with jest-preset-angular 17.0.3 and the configuration in Jest setup. With jest-preset-angular 14.6.2 or 15.0.0 it fails with A dynamic import callback was invoked without --experimental-vm-modules. Under Karma it runs.

Do this instead: replace the compat service.

Keeping the real module with importOriginal

Applies to the modular API.

In Vitest a mock can also be built from the real module, to replace one function and keep the rest:

vi.mock('@angular/fire/auth', async importOriginal => ({
  ...(await importOriginal<typeof import('@angular/fire/auth')>()),
  authState: vi.fn(() => of({ uid: 'user-1' })),
}));

Under the Angular CLI this works only while one spec file imports the component under test. As soon as a second spec file imports the same component, the file with the mock fails to load with There was an error when mocking a module, caused by ReferenceError: Cannot access '__vi_import_1__' before initialization. In an Angular 22 app that uses zone.js it fails even in a single spec file, because the factory is async (see the next section).

Do this instead: list the names the code imports, as in Mock the module. In Jest, spreading jest.requireActual('@angular/fire/auth') into the mock works.

vi.mock in an Angular 22 app that uses zone.js

Applies to both APIs.

In an Angular 22 app created with ng new --no-zoneless (@angular/build 22.3.0, Vitest 5.1.2), a spec file that calls vi.mock fails to load when the same file contains an async function. The error is 1 call in "..." was defined outside of the module's top level scope. This happens for any mocked package, with or without AngularFire. The same file on Angular 21 with Vitest 4 runs and prints a warning that the call is not at the top level of the module. A zoneless Angular 22 app is not affected.

Do this instead: keep async and await out of a spec file that calls vi.mock, and return the promise from each test, as the example in Mock the module does. A fake Auth object and real services with made-up options need no vi.mock, so their spec files can use async.

Jest setup

With Jest 30 and the jsdom test environment, a test that imports firebase/auth or @angular/fire/auth fails before it runs:

ReferenceError: fetch is not defined

Jest 30 loads the Node build of Firebase Auth, which expects fetch to exist, and jsdom does not provide it. Make Jest load the browser build with a resolver file next to jest.config.js:

// jest.resolver.js
const firebaseAuthPackages = ['@firebase/auth', '@firebase/auth/internal', '@firebase/auth-compat'];

module.exports = (request, options) => {
  const conditions = firebaseAuthPackages.includes(request) ? ['browser', 'require', 'default'] : options.conditions;
  return options.defaultResolver(request, { ...options, conditions });
};

Then reference the file in jest.config.js:

module.exports = {
  // the rest of your Jest configuration
  resolver: '<rootDir>/jest.resolver.js',
};

The modular API loads @firebase/auth. The compat API loads @firebase/auth-compat, which in turn loads @firebase/auth/internal. Jest 29 does not need the resolver.

With that in place, the patterns on this page work in Jest. The module mock is written with jest in place of vi, as shown in Mock the module.

Karma and Jasmine setup

Karma runs the tests in a real browser, and AngularFire needs no extra test configuration there. Everything in this section gave the same results with the @angular/build:karma builder, with @angular/build:unit-test and "runner": "karma", and with the older @angular-devkit/build-angular:karma builder.

What works as written

  • Real services with made-up options, with the same limitations. A sign-in call reaches Google and rejects with auth/api-key-not-valid.-please-pass-a-valid-api-key., as under Vitest.
  • Replacing a compat service.
  • The real compat AngularFireAuth with AngularFireModule.initializeApp(fakeOptions). It does not run under Vitest, but it runs in Karma's browser, where authState emits null.
  • The error messages under What does not work for fake Firestore and Storage objects and for a missing Firebase app are the same in Chrome. Firefox words the Storage error differently.

The fake Auth example needs one change

Applies to the modular API.

The fake Auth object works under Jasmine, but the last line of its example does not compile. Jasmine's types check the expected value against User, and the build stops with TS2345: Argument of type '{ uid: string; getIdToken: () => Promise<string>; }' is not assignable to parameter of type 'Expected<User | null>'. Give expect the type unknown:

expect<unknown>(await firstValueFrom(component.user$)).toEqual(fakeUser);

Jasmine has no module mock

Applies to the modular API.

Jasmine has no equivalent of vi.mock, and its spies cannot replace a function that AngularFire exports.

  • spyOn(fireAuth, 'authState') throws <spyOn> : authState is not declared writable or has no setter.
  • spyOnProperty(fireAuth, 'authState', 'get') throws <spyOnProperty> : authState is not declared configurable.

spyOn throws the same error for functions imported from firebase/auth directly, so this is not specific to AngularFire.

Do this instead: for the signed-in state, give Auth a fake object. For everything else, such as a sign-in call or a Firestore read, use one of the two patterns below. Jasmine's own module mocking guide recommends the same two for Angular.

Put the AngularFire calls in a service

Keep the AngularFire calls in a service of your own:

// todo-list.ts
import { Component, inject, Injectable } from '@angular/core';
import { collection, collectionData, Firestore } from '@angular/fire/firestore';

@Injectable({ providedIn: 'root' })
export class TodoStore {
  private readonly firestore = inject(Firestore);
  readonly todos$ = collectionData(collection(this.firestore, 'todos'));
}

@Component({ selector: 'app-todo-list', template: '' })
export class TodoList {
  readonly todos$ = inject(TodoStore).todos$;
}

Then replace the service through TestBed providers:

import { TestBed } from '@angular/core/testing';
import { firstValueFrom, of } from 'rxjs';
import { TodoList, TodoStore } from './todo-list';

it('lists the todos', async () => {
  TestBed.configureTestingModule({
    providers: [{ provide: TodoStore, useValue: { todos$: of([{ title: 'Write tests' }]) } }],
  });
  const component = TestBed.createComponent(TodoList).componentInstance;

  expect(await firstValueFrom(component.todos$)).toEqual([{ title: 'Write tests' }]);
});

Keep spyOn with a wrapper object

To keep spyOn, export an object that holds the AngularFire functions:

// auth-functions.ts
import { signInWithEmailAndPassword } from '@angular/fire/auth';

export const authFunctions = { signInWithEmailAndPassword };

The code under test calls authFunctions.signInWithEmailAndPassword(...) in place of signInWithEmailAndPassword(...). A test can then replace the function, and Auth can be provided as an empty object:

spyOn(authFunctions, 'signInWithEmailAndPassword').and.rejectWith(new Error('auth/wrong-password'));

Every spec file shares one page

Applies to both APIs.

Karma loads every spec file into one browser page, and Jasmine runs the tests in random order by default. A Firebase app created in one spec file is still registered when the next one runs. If two spec files use different options, the one that runs second fails with Firebase App named '[DEFAULT]' already exists with different options, and which one that is changes from run to run. When both files use the compat API there is no error. AngularFireModule.initializeApp in the second file gets the app the first file created, with the first file's options.

Using one set of options in the whole project works.

If the tests use only the modular API and need more than one set, add the cleanup hook from The app outlives the test. Under Karma a top-level afterEach in one spec file runs after every test of every spec file. One copy is enough, as long as that spec file is part of every run.

Leave the hook out of a project whose tests create an app with AngularFireModule.initializeApp. Under Karma it runs after those tests too, and it breaks them in the way The app outlives the test describes.

Moving to Vitest

From Jest

Vitest's Migrating from Jest page lists the differences between the two APIs. Angular's Migrating from Karma to Vitest guide is written for projects coming from Karma. It shows how to install Vitest and switch the test target in angular.json.

From Karma and Jasmine

Follow Angular's Migrating from Karma to Vitest guide. It includes the refactor-jasmine-vitest schematic, which Angular marks as experimental and which rewrites Jasmine calls such as spyOn to their Vitest forms.

Three things change after migrating to Vitest:

  • The real compat AngularFireAuth no longer runs. Replace the compat service in the tests that use it.
  • A cleanup hook written once for the whole Karma run now covers only its own spec file. Two ways to handle it (either works):
    • Move it to a file listed in the setupFiles option of the test target. If using @angular/build 21.2, add that file to include in tsconfig.spec.json as well. Or
    • Copy it into every spec file that creates an app.
  • A module mock can take over the job of a wrapper object. Read the notes under Mock the module before using vi.mock.