diff --git a/README.md b/README.md index a47022fac..d75536d08 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,8 @@ The converter is what gives the read its type. `collection()` alone returns an u [Deploying SSR to App Hosting](docs/app-hosting.md) - Deploy a server-rendered app to Firebase App Hosting, and avoid the silent SSR-to-CSR fallback. +[Testing](docs/testing.md) - Unit test components and services that use AngularFire, with Vitest or Jest. + [Contributing](CONTRIBUTING.md) [Stackblitz Template](https://stackblitz.com/edit/angular-fire-start) - A runnable AngularFire example. Add your own Firebase configuration to connect it to your project. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 000000000..a9718a9c6 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,382 @@ + +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, and Jest. + +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](#choose-a-test-runner) +- [Decide how much of Firebase the test runs](#decide-how-much-of-firebase-the-test-runs) +- [Use real services with made-up options](#use-real-services-with-made-up-options) + - [Limitations](#limitations) + - [There is no backend](#there-is-no-backend) + - [The app outlives the test](#the-app-outlives-the-test) +- [Replace AngularFire in the test](#replace-angularfire-in-the-test) + - [Mock the module](#mock-the-module) + - [Vitest example](#vitest-example) + - [Keep `async` out of the spec file](#keep-async-out-of-the-spec-file) + - [Turn on test isolation](#turn-on-test-isolation) + - [Mock the package, not your own files](#mock-the-package-not-your-own-files) + - [Jest example](#jest-example) + - [Give `Auth` a fake object](#give-auth-a-fake-object) + - [Replace a compat service](#replace-a-compat-service) +- [What does not work](#what-does-not-work) + - [Spying on AngularFire functions](#spying-on-angularfire-functions) + - [Fake `Firestore` and `Storage` objects](#fake-firestore-and-storage-objects) + - [No Firebase App has been created](#no-firebase-app-has-been-created) + - [The compat `AngularFireAuth` with a real app](#the-compat-angularfireauth-with-a-real-app) + - [Keeping the real module with `importOriginal`](#keeping-the-real-module-with-importoriginal) + - [`vi.mock` in an Angular 22 app that uses zone.js](#vimock-in-an-angular-22-app-that-uses-zonejs) +- [Jest setup](#jest-setup) +- [Moving from Jest to Vitest](#moving-from-jest-to-vitest) + +## 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](#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](#jest-setup). + +The examples below test this component: + +```ts +// 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](#use-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](#replace-angularfire-in-the-test) | The test needs a specific user or specific data. | +| [The Firebase Local Emulator Suite](https://firebase.google.com/docs/emulator-suite) | The test needs a real backend. See the emulator sections in [Authentication](auth.md#connecting-the-emulator-suite) and [Realtime Database](database.md#connecting-to-the-emulator-suite). | + +## 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: + +```ts +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](#replace-angularfire-in-the-test) 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](#turn-on-test-isolation) is on. + +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: + +```ts +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](zones.md#logging). 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 + +```ts +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](#vimock-in-an-angular-22-app-that-uses-zonejs). + +#### 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`: + +```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`: + +```ts +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. + +```ts +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. + +```ts +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); +}); +``` + +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](#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: + +```ts +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](#mock-the-module). + +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. + +```ts +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](#use-real-services-with-made-up-options) when the code only builds references, and [mock the module](#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](#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`. + +Do this instead: [replace the compat service](#replace-a-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: + +```ts +vi.mock('@angular/fire/auth', async importOriginal => ({ + ...(await importOriginal()), + 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](#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](#mock-the-module) does. A [fake `Auth` object](#give-auth-a-fake-object) and [real services with made-up options](#use-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`: + +```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`: + +```js +module.exports = { + // the rest of your Jest configuration + resolver: '/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](#mock-the-module). + +## Moving from Jest to Vitest + +Vitest's [Migrating from Jest](https://vitest.dev/guide/migration/jest) page lists the differences between the two APIs. Angular's [Migrating from Karma to Vitest](https://angular.dev/guide/testing/migrating-to-vitest) guide is written for projects coming from Karma. It shows how to install Vitest and switch the `test` target in `angular.json`.