diff --git a/README.md b/README.md index 6d8c455cf..f566ae43f 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, Jest, or Karma. + [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/database.md b/docs/database.md index dcc1f39ea..6b2bd5cf8 100644 --- a/docs/database.md +++ b/docs/database.md @@ -60,53 +60,53 @@ AngularFire provides observables to allow convenient use of the Realtime Databas The `object()` function creates an observable that emits object changes. -| | | -|-----------------|------------------------------------------| -| **function** | `object(ref)` | -| **params** | ref: `Reference` | -| **return** | `Observable` | +| | | +|-----------------|-----------------------------------| +| **function** | `object(query)` | +| **params** | query: `DatabaseReference\|Query` | +| **return** | `Observable` | ### `objectVal` -The `objectVal` function creates an observable that emits an array of object values, optionally with a mapped key. +The `objectVal()` function creates an observable that emits the value of the node (an object, a primitive, or `null` if it does not exist), optionally with its key mapped to `keyField`. -| | | -|-----------------|-------------------------------------------------------| -| **function** | `objectVal(query, options?)` | -| **params** | query: `Reference\|Query`, options?: { keyField?: `string` } | -| **return** | `Observable` | +| | | +|-----------------|----------------------------------------------------------------------| +| **function** | `objectVal(query, options?)` | +| **params** | query: `DatabaseReference\|Query`, options?: `{ keyField?: string }` | +| **return** | `Observable` | ### `list` The `list()` function creates an observable that emits a sorted array for each child event change. The optional `events` parameter will filter which child events populate the array. -| | | -|-----------------|-------------------------------------------------------| -| **function** | `list(ref, options?)` | -| **params** | ref: `Reference\|Query`, options?: { events?: `ListenEvent[]` } | -| **return** | `Observable` | +| | | +|-----------------|---------------------------------------------------------------------------| +| **function** | `list(query, options?)` | +| **params** | query: `DatabaseReference\|Query`, options?: `{ events?: ListenEvent[] }` | +| **return** | `Observable` | ### `listVal` -The `listVal()` function creates an observable that emits an object mapped to its value, and optionally its key. +The `listVal()` function creates an observable that emits an array of child values, optionally with each item's key mapped to `keyField`. -| | | -|-----------------|-------------------------------------------------------| -| **function** | `listVal(query, options?)` | -| **params** | ref: `Reference\|Query`, options?: { keyField?: `string` } | -| **return** | `Observable` | +| | | +|-----------------|----------------------------------------------------------------------| +| **function** | `listVal(query, options?)` | +| **params** | query: `DatabaseReference\|Query`, options?: `{ keyField?: string }` | +| **return** | `Observable` | ### `stateChanges` -The `stateChanges()` function creates an observable that emits each time a change occurs at the reference or query passed. This is useful for tracking the changes in your list. The optional `events` parameter will filter which child events populate the array. +The `stateChanges()` function creates an observable that emits each time a change occurs at the reference or query passed. This is useful for tracking the changes in your list. The optional `events` parameter will filter which child events are emitted. It emits only on child events, which an empty list never produces, so it does not hold the application unstable and a server render does not wait for it. Use `list()` when the render should wait for a list's initial contents. -| | | -|-----------------|------------------------------------------------------| -| **function** | `stateChanges(ref, options?)` | -| **params** | ref: `Reference\|Query`, options:? { events?: `ListenEvent[]` } | -| **return** | `Observable` | +| | | +|-----------------|---------------------------------------------------------------------------| +| **function** | `stateChanges(query, options?)` | +| **params** | query: `DatabaseReference\|Query`, options?: `{ events?: ListenEvent[] }` | +| **return** | `Observable` | ### `auditTrail` @@ -114,11 +114,11 @@ The `auditTrail()` function creates an observable that emits the entire state tr Like `stateChanges()`, it waits for child events, so it does not hold the application unstable and a server render does not wait for it. -| | | -|-----------------|------------------------------------------------------| -| **function** | `auditTrail(ref, options?)` | -| **params** | ref: `Reference\|Query`, options?: { events?: `ListenEvent[]` } | -| **return** | `Observable` | +| | | +|-----------------|---------------------------------------------------------------------------| +| **function** | `auditTrail(query, options?)` | +| **params** | query: `DatabaseReference\|Query`, options?: `{ events?: ListenEvent[] }` | +| **return** | `Observable` | ### `fromRef` @@ -126,11 +126,11 @@ The `fromRef()` function creates an observable that emits reference changes. With `ListenEvent.value` it holds the application unstable until the first value is emitted, so a server render waits for the data. With a child event it does not, because it may never emit. -| | | -|-----------------|------------------------------------------| -| **function** | `fromRef(ref, event)` | -| **params** | ref: `Reference\|Query`, event: `ListenEvent` | -| **return** | `Observable` | +| | | +|-----------------|-------------------------------------------------------| +| **function** | `fromRef(ref, event)` | +| **params** | ref: `DatabaseReference\|Query`, event: `ListenEvent` | +| **return** | `Observable` | ## Connecting to the emulator suite @@ -154,8 +154,8 @@ export const appConfig: ApplicationConfig = { ## Working with multiple instances ```ts -import { ApplicationConfig } from '@angular/core'; -import { provideFirebaseApp, FirebaseApp, initializeApp } from '@angular/fire/app'; +import { ApplicationConfig, inject } from '@angular/core'; +import { FirebaseApp, initializeApp, provideFirebaseApp } from '@angular/fire/app'; import { getDatabase, provideDatabase } from '@angular/fire/database'; const DATABASE_SHARD_URLS = [ @@ -167,11 +167,11 @@ const DATABASE_SHARD_URLS = [ export const appConfig: ApplicationConfig = { providers: [ provideFirebaseApp(() => initializeApp({ ... })), - provideDatabase((app: FirebaseApp) => getDatabase(app, DATABASE_SHARD_URLS[0])), - provideDatabase((app: FirebaseApp) => getDatabase(app, DATABASE_SHARD_URLS[1])), - provideDatabase((app: FirebaseApp) => getDatabase(app, DATABASE_SHARD_URLS[2])), - ] -} + provideDatabase(() => getDatabase(inject(FirebaseApp), DATABASE_SHARD_URLS[0])), + provideDatabase(() => getDatabase(inject(FirebaseApp), DATABASE_SHARD_URLS[1])), + provideDatabase(() => getDatabase(inject(FirebaseApp), DATABASE_SHARD_URLS[2])), + ], +}; ``` ```ts diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 000000000..e7457d4bd --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,510 @@ + +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](#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) +- [Karma and Jasmine setup](#karma-and-jasmine-setup) + - [What works as written](#what-works-as-written) + - [The fake `Auth` example needs one change](#the-fake-auth-example-needs-one-change) + - [Jasmine has no module mock](#jasmine-has-no-module-mock) + - [Put the AngularFire calls in a service](#put-the-angularfire-calls-in-a-service) + - [Keep `spyOn` with a wrapper object](#keep-spyon-with-a-wrapper-object) + - [Every spec file shares one page](#every-spec-file-shares-one-page) +- [Moving to Vitest](#moving-to-vitest) + - [From Jest](#from-jest) + - [From Karma and Jasmine](#from-karma-and-jasmine) + +## 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). + +**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](#karma-and-jasmine-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. Under Karma the app is always still registered. See [Every spec file shares one page](#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: + +```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); +}); +``` + +Under Jasmine the last line of this test needs one change. See [The fake `Auth` example needs one change](#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](#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). Jasmine's `spyOn` fails too and Jasmine has no module mock. See [Jasmine has no module mock](#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. + +```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`. Under Karma it runs. + +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). + +## 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](#use-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](#replace-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](#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](#give-auth-a-fake-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; }' is not assignable to parameter of type 'Expected'`. Give `expect` the type `unknown`: + +```ts +expect(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 ` : authState is not declared writable or has no setter`. +- `spyOnProperty(fireAuth, 'authState', 'get')` throws ` : 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](#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](https://jasmine.github.io/tutorials/module_mocking#angular) recommends the same two for Angular. + +#### Put the AngularFire calls in a service + +Keep the AngularFire calls in a service of your own: + +```ts +// 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: + +```ts +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: + +```ts +// 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: + +```ts +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](#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](#the-app-outlives-the-test) describes. + +## Moving to Vitest + +### From Jest + +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`. + +### From Karma and Jasmine + +Follow Angular's [Migrating from Karma to Vitest](https://angular.dev/guide/testing/migrating-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](#replace-a-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](#mock-the-module) before using `vi.mock`. diff --git a/src/core.ts b/src/core.ts index e0ad8f7f5..f8c7e1533 100644 --- a/src/core.ts +++ b/src/core.ts @@ -18,7 +18,10 @@ export function ɵgetDefaultInstanceOf(identifier: string, provided: if (provided) { // Was provide* only called once? If so grab that if (provided.length === 1) { return provided[0]; } - const providedUsingDefaultApp = provided.filter((it: any) => it.app === defaultApp); + + // An entry is null where its product is unavailable, such as messaging on the server. + const providedUsingDefaultApp = provided.filter((it: any) => it?.app === defaultApp); + // Was provide* only called once, using the default app? If so use that if (providedUsingDefaultApp.length === 1) { return providedUsingDefaultApp[0]; } } diff --git a/src/messaging/messaging.module.ts b/src/messaging/messaging.module.ts index 0942e053a..7a0f34c4e 100644 --- a/src/messaging/messaging.module.ts +++ b/src/messaging/messaging.module.ts @@ -26,8 +26,16 @@ export function defaultMessagingInstanceFactory(provided: FirebaseMessaging[]|un export function messagingInstanceFactory(fn: (injector: Injector) => FirebaseMessaging) { return (zone: NgZone, injector: Injector, platformId: object) => { if (isPlatformServer(platformId)) { return null; } - const messaging = zone.runOutsideAngular(() => fn(injector)); - return new Messaging(messaging); + + try { + const messaging = zone.runOutsideAngular(() => fn(injector)); + return new Messaging(messaging); + } catch (error) { + // Firebase's `getMessaging` throws where `navigator.serviceWorker` is missing. + if ('serviceWorker' in navigator) { throw error; } + + return null; + } }; } diff --git a/src/messaging/messaging.spec.ts b/src/messaging/messaging.spec.ts index 5a48de626..e0e57455c 100644 --- a/src/messaging/messaging.spec.ts +++ b/src/messaging/messaging.spec.ts @@ -38,4 +38,79 @@ describe('Messaging', () => { }); + describe('when the factory throws', () => { + + it('should rethrow in a browser with service workers', () => { + TestBed.configureTestingModule({ + providers: [ + provideFirebaseApp(() => initializeApp(COMMON_CONFIG, rando())), + provideMessaging(() => { throw new Error('thrown by the factory'); }), + ], + }); + + expect(() => TestBed.inject(Messaging)).toThrowError('thrown by the factory'); + }); + + }); + + describe('in a browser without service workers', () => { + let serviceWorkerProperty: PropertyDescriptor | undefined; + + beforeEach(() => { + // A page that is not a secure context has no `serviceWorker` property at all. + serviceWorkerProperty = Object.getOwnPropertyDescriptor(Navigator.prototype, 'serviceWorker'); + Reflect.deleteProperty(Navigator.prototype, 'serviceWorker'); + + appName = rando(); + }); + + afterEach(() => { + if (serviceWorkerProperty) { + Object.defineProperty(Navigator.prototype, 'serviceWorker', serviceWorkerProperty); + } + }); + + it('should inject null where getMessaging throws', () => { + TestBed.configureTestingModule({ + providers: [ + provideFirebaseApp(() => initializeApp(COMMON_CONFIG, appName)), + provideMessaging(() => getMessaging(getApp(appName))), + ], + }); + + expect('serviceWorker' in navigator).toBeFalse(); + expect(TestBed.inject(Messaging)).toBeNull(); + }); + + it('should inject what the factory returns when it does not throw', () => { + let returnedByFactory: Messaging | undefined; + + TestBed.configureTestingModule({ + providers: [ + provideFirebaseApp(() => initializeApp(COMMON_CONFIG, appName)), + provideMessaging(() => { + returnedByFactory = { app: getApp(appName) }; + return returnedByFactory; + }), + ], + }); + + expect(TestBed.inject(Messaging)).toBe(returnedByFactory); + }); + + it('should inject null with two registrations', () => { + TestBed.configureTestingModule({ + providers: [ + provideFirebaseApp(() => initializeApp(COMMON_CONFIG)), + provideMessaging(() => getMessaging()), + provideFirebaseApp(() => initializeApp(COMMON_CONFIG, appName)), + provideMessaging(() => getMessaging(getApp(appName))), + ], + }); + + expect(TestBed.inject(Messaging)).toBeNull(); + }); + + }); + });