|
4 | 4 |
|
5 | 5 | # Testing |
6 | 6 |
|
7 | | -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. |
| 7 | +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. |
8 | 8 |
|
9 | 9 | 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. |
10 | 10 |
|
@@ -33,14 +33,25 @@ Each pattern says whether it applies to the modular API (`@angular/fire/auth` an |
33 | 33 | - [Keeping the real module with `importOriginal`](#keeping-the-real-module-with-importoriginal) |
34 | 34 | - [`vi.mock` in an Angular 22 app that uses zone.js](#vimock-in-an-angular-22-app-that-uses-zonejs) |
35 | 35 | - [Jest setup](#jest-setup) |
36 | | -- [Moving from Jest to Vitest](#moving-from-jest-to-vitest) |
| 36 | +- [Karma and Jasmine setup](#karma-and-jasmine-setup) |
| 37 | + - [What works as written](#what-works-as-written) |
| 38 | + - [The fake `Auth` example needs one change](#the-fake-auth-example-needs-one-change) |
| 39 | + - [Jasmine has no module mock](#jasmine-has-no-module-mock) |
| 40 | + - [Put the AngularFire calls in a service](#put-the-angularfire-calls-in-a-service) |
| 41 | + - [Keep `spyOn` with a wrapper object](#keep-spyon-with-a-wrapper-object) |
| 42 | + - [Every spec file shares one page](#every-spec-file-shares-one-page) |
| 43 | +- [Moving to Vitest](#moving-to-vitest) |
| 44 | + - [From Jest](#from-jest) |
| 45 | + - [From Karma and Jasmine](#from-karma-and-jasmine) |
37 | 46 |
|
38 | 47 | ## Choose a test runner |
39 | 48 |
|
40 | 49 | **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). |
41 | 50 |
|
42 | 51 | **Jest** works too. Jest 30 needs one addition to its configuration before a test can import `firebase/auth`. See [Jest setup](#jest-setup). |
43 | 52 |
|
| 53 | +**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). |
| 54 | + |
44 | 55 | The examples below test this component: |
45 | 56 |
|
46 | 57 | ```ts |
@@ -102,7 +113,7 @@ A call that needs one fails. `signInWithEmailAndPassword` rejects with `auth/api |
102 | 113 |
|
103 | 114 | #### The app outlives the test |
104 | 115 |
|
105 | | -`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. |
| 116 | +`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). |
106 | 117 |
|
107 | 118 | Using the same options again is fine. Using different options in a later test throws `Firebase App named '[DEFAULT]' already exists with different options`. |
108 | 119 |
|
@@ -243,6 +254,8 @@ it('shows the signed-in user', async () => { |
243 | 254 | }); |
244 | 255 | ``` |
245 | 256 |
|
| 257 | +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). |
| 258 | + |
246 | 259 | 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. |
247 | 260 |
|
248 | 261 | 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 ` |
273 | 286 |
|
274 | 287 | `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. |
275 | 288 |
|
276 | | -Do this instead: [mock the module](#mock-the-module). |
| 289 | +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). |
277 | 290 |
|
278 | 291 | 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. |
279 | 292 |
|
@@ -315,7 +328,7 @@ A test that provides nothing at all fails differently, with Angular's `` NG0201: |
315 | 328 |
|
316 | 329 | *Applies to the compat API.* |
317 | 330 |
|
318 | | -`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`. |
| 331 | +`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. |
319 | 332 |
|
320 | 333 | Do this instead: [replace the compat service](#replace-a-compat-service). |
321 | 334 |
|
@@ -377,6 +390,121 @@ The modular API loads `@firebase/auth`. The compat API loads `@firebase/auth-com |
377 | 390 |
|
378 | 391 | 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). |
379 | 392 |
|
380 | | -## Moving from Jest to Vitest |
| 393 | +## Karma and Jasmine setup |
| 394 | + |
| 395 | +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. |
| 396 | + |
| 397 | +### What works as written |
| 398 | + |
| 399 | +- [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. |
| 400 | +- [Replacing a compat service](#replace-a-compat-service). |
| 401 | +- 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`. |
| 402 | +- 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. |
| 403 | + |
| 404 | +### The fake `Auth` example needs one change |
| 405 | + |
| 406 | +*Applies to the modular API.* |
| 407 | + |
| 408 | +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<string>; }' is not assignable to parameter of type 'Expected<User | null>'`. Give `expect` the type `unknown`: |
| 409 | + |
| 410 | +```ts |
| 411 | +expect<unknown>(await firstValueFrom(component.user$)).toEqual(fakeUser); |
| 412 | +``` |
| 413 | + |
| 414 | +### Jasmine has no module mock |
| 415 | + |
| 416 | +*Applies to the modular API.* |
| 417 | + |
| 418 | +Jasmine has no equivalent of `vi.mock`, and its spies cannot replace a function that AngularFire exports. |
| 419 | + |
| 420 | +- `spyOn(fireAuth, 'authState')` throws `<spyOn> : authState is not declared writable or has no setter`. |
| 421 | +- `spyOnProperty(fireAuth, 'authState', 'get')` throws `<spyOnProperty> : authState is not declared configurable`. |
| 422 | + |
| 423 | +`spyOn` throws the same error for functions imported from `firebase/auth` directly, so this is not specific to AngularFire. |
| 424 | + |
| 425 | +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. |
| 426 | + |
| 427 | +#### Put the AngularFire calls in a service |
| 428 | + |
| 429 | +Keep the AngularFire calls in a service of your own: |
| 430 | + |
| 431 | +```ts |
| 432 | +// todo-list.ts |
| 433 | +import { Component, inject, Injectable } from '@angular/core'; |
| 434 | +import { collection, collectionData, Firestore } from '@angular/fire/firestore'; |
| 435 | + |
| 436 | +@Injectable({ providedIn: 'root' }) |
| 437 | +export class TodoStore { |
| 438 | + private readonly firestore = inject(Firestore); |
| 439 | + readonly todos$ = collectionData(collection(this.firestore, 'todos')); |
| 440 | +} |
| 441 | + |
| 442 | +@Component({ selector: 'app-todo-list', template: '' }) |
| 443 | +export class TodoList { |
| 444 | + readonly todos$ = inject(TodoStore).todos$; |
| 445 | +} |
| 446 | +``` |
| 447 | + |
| 448 | +Then replace the service through `TestBed` providers: |
| 449 | + |
| 450 | +```ts |
| 451 | +import { TestBed } from '@angular/core/testing'; |
| 452 | +import { firstValueFrom, of } from 'rxjs'; |
| 453 | +import { TodoList, TodoStore } from './todo-list'; |
| 454 | + |
| 455 | +it('lists the todos', async () => { |
| 456 | + TestBed.configureTestingModule({ |
| 457 | + providers: [{ provide: TodoStore, useValue: { todos$: of([{ title: 'Write tests' }]) } }], |
| 458 | + }); |
| 459 | + const component = TestBed.createComponent(TodoList).componentInstance; |
| 460 | + |
| 461 | + expect(await firstValueFrom(component.todos$)).toEqual([{ title: 'Write tests' }]); |
| 462 | +}); |
| 463 | +``` |
| 464 | + |
| 465 | +#### Keep `spyOn` with a wrapper object |
| 466 | + |
| 467 | +To keep `spyOn`, export an object that holds the AngularFire functions: |
| 468 | + |
| 469 | +```ts |
| 470 | +// auth-functions.ts |
| 471 | +import { signInWithEmailAndPassword } from '@angular/fire/auth'; |
| 472 | + |
| 473 | +export const authFunctions = { signInWithEmailAndPassword }; |
| 474 | +``` |
| 475 | + |
| 476 | +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: |
| 477 | + |
| 478 | +```ts |
| 479 | +spyOn(authFunctions, 'signInWithEmailAndPassword').and.rejectWith(new Error('auth/wrong-password')); |
| 480 | +``` |
| 481 | + |
| 482 | +### Every spec file shares one page |
| 483 | + |
| 484 | +*Applies to both APIs.* |
| 485 | + |
| 486 | +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. |
| 487 | + |
| 488 | +Using one set of options in the whole project works. |
| 489 | + |
| 490 | +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. |
| 491 | + |
| 492 | +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. |
| 493 | + |
| 494 | +## Moving to Vitest |
| 495 | + |
| 496 | +### From Jest |
381 | 497 |
|
382 | 498 | 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`. |
| 499 | + |
| 500 | +### From Karma and Jasmine |
| 501 | + |
| 502 | +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. |
| 503 | + |
| 504 | +Three things change after migrating to Vitest: |
| 505 | + |
| 506 | +- The real compat `AngularFireAuth` no longer runs. [Replace the compat service](#replace-a-compat-service) in the tests that use it. |
| 507 | +- A cleanup hook written once for the whole Karma run now covers only its own spec file. Two ways to handle it (either works): |
| 508 | + - 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 |
| 509 | + - Copy it into every spec file that creates an app. |
| 510 | +- 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`. |
0 commit comments