diff --git a/README.md b/README.md index d75536d08..2a8a29a4f 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ 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. +[Testing](docs/testing.md) - Unit test components and services that use AngularFire, with Vitest, Jest, or Karma. [Contributing](CONTRIBUTING.md) diff --git a/docs/testing.md b/docs/testing.md index a9718a9c6..e7457d4bd 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4,7 +4,7 @@ # 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. +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. @@ -33,7 +33,16 @@ Each pattern says whether it applies to the modular API (`@angular/fire/auth` an - [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) +- [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 @@ -41,6 +50,8 @@ Each pattern says whether it applies to the modular API (`@angular/fire/auth` an **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 @@ -102,7 +113,7 @@ A call that needs one fails. `signInWithEmailAndPassword` rejects with `auth/api #### 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. +`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`. @@ -243,6 +254,8 @@ it('shows the signed-in user', async () => { }); ``` +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. @@ -273,7 +286,7 @@ A component that injects `AngularFireAuth` then reads `{ uid: 'user-1' }` from ` `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). +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. @@ -315,7 +328,7 @@ A test that provides nothing at all fails differently, with Angular's `` NG0201: *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`. +`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). @@ -377,6 +390,121 @@ The modular API loads `@firebase/auth`. The compat API loads `@firebase/auth-com 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 +## 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`.