Skip to content

Commit 4627bab

Browse files
docs: add a unit testing guide (#3855)
* docs: add a unit testing guide AngularFire had no testing guidance in docs/ or the README, and four issues have asked for it. docs/testing.md covers Vitest and Jest: real services built from made-up options, three ways to replace AngularFire in a test, the setups that do not work with their error text, and the resolver file Jest 30 needs. The README links to it. Fixes #3668
1 parent 07d7ee4 commit 4627bab

2 files changed

Lines changed: 384 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ The converter is what gives the read its type. `collection()` alone returns an u
7878

7979
[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.
8080

81+
[Testing](docs/testing.md) - Unit test components and services that use AngularFire, with Vitest or Jest.
82+
8183
[Contributing](CONTRIBUTING.md)
8284

8385
[Stackblitz Template](https://stackblitz.com/edit/angular-fire-start) - A runnable AngularFire example. Add your own Firebase configuration to connect it to your project.

‎docs/testing.md‎

Lines changed: 382 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,382 @@
1+
<small>
2+
<a href="https://github.com/angular/angularfire">AngularFire</a> &#10097; <a href="../README.md#developer-guide">Developer Guide</a> &#10097; Testing
3+
</small>
4+
5+
# Testing
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.
8+
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+
11+
## Contents
12+
13+
- [Choose a test runner](#choose-a-test-runner)
14+
- [Decide how much of Firebase the test runs](#decide-how-much-of-firebase-the-test-runs)
15+
- [Use real services with made-up options](#use-real-services-with-made-up-options)
16+
- [Limitations](#limitations)
17+
- [There is no backend](#there-is-no-backend)
18+
- [The app outlives the test](#the-app-outlives-the-test)
19+
- [Replace AngularFire in the test](#replace-angularfire-in-the-test)
20+
- [Mock the module](#mock-the-module)
21+
- [Vitest example](#vitest-example)
22+
- [Keep `async` out of the spec file](#keep-async-out-of-the-spec-file)
23+
- [Turn on test isolation](#turn-on-test-isolation)
24+
- [Mock the package, not your own files](#mock-the-package-not-your-own-files)
25+
- [Jest example](#jest-example)
26+
- [Give `Auth` a fake object](#give-auth-a-fake-object)
27+
- [Replace a compat service](#replace-a-compat-service)
28+
- [What does not work](#what-does-not-work)
29+
- [Spying on AngularFire functions](#spying-on-angularfire-functions)
30+
- [Fake `Firestore` and `Storage` objects](#fake-firestore-and-storage-objects)
31+
- [No Firebase App has been created](#no-firebase-app-has-been-created)
32+
- [The compat `AngularFireAuth` with a real app](#the-compat-angularfireauth-with-a-real-app)
33+
- [Keeping the real module with `importOriginal`](#keeping-the-real-module-with-importoriginal)
34+
- [`vi.mock` in an Angular 22 app that uses zone.js](#vimock-in-an-angular-22-app-that-uses-zonejs)
35+
- [Jest setup](#jest-setup)
36+
- [Moving from Jest to Vitest](#moving-from-jest-to-vitest)
37+
38+
## Choose a test runner
39+
40+
**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+
42+
**Jest** works too. Jest 30 needs one addition to its configuration before a test can import `firebase/auth`. See [Jest setup](#jest-setup).
43+
44+
The examples below test this component:
45+
46+
```ts
47+
// user-badge.ts
48+
import { Component, inject } from '@angular/core';
49+
import { Auth, authState } from '@angular/fire/auth';
50+
51+
@Component({ selector: 'app-user-badge', template: '' })
52+
export class UserBadge {
53+
private readonly auth = inject(Auth);
54+
readonly user$ = authState(this.auth);
55+
}
56+
```
57+
58+
## Decide how much of Firebase the test runs
59+
60+
| Approach | Use it when |
61+
|---|---|
62+
| [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. |
63+
| [Replace AngularFire in the test](#replace-angularfire-in-the-test) | The test needs a specific user or specific data. |
64+
| [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). |
65+
66+
## Use real services with made-up options
67+
68+
*Applies to the modular API.*
69+
70+
Provide AngularFire the way the app does, with an options object that belongs to no real project:
71+
72+
```ts
73+
import { TestBed } from '@angular/core/testing';
74+
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
75+
import { getAuth, provideAuth } from '@angular/fire/auth';
76+
import { firstValueFrom } from 'rxjs';
77+
import { UserBadge } from './user-badge';
78+
79+
const fakeOptions = { apiKey: 'fake-api-key', projectId: 'demo-project' };
80+
81+
describe('UserBadge', () => {
82+
it('starts signed out', async () => {
83+
TestBed.configureTestingModule({
84+
providers: [provideFirebaseApp(() => initializeApp(fakeOptions)), provideAuth(() => getAuth())],
85+
});
86+
const component = TestBed.createComponent(UserBadge).componentInstance;
87+
88+
expect(await firstValueFrom(component.user$)).toBeNull();
89+
});
90+
});
91+
```
92+
93+
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'`.
94+
95+
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`.
96+
97+
### Limitations
98+
99+
#### There is no backend
100+
101+
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.
102+
103+
#### The app outlives the test
104+
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.
106+
107+
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+
109+
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:
110+
111+
```ts
112+
import { TestBed } from '@angular/core/testing';
113+
import { deleteApp, getApps } from '@angular/fire/app';
114+
115+
afterEach(async () => {
116+
await TestBed.runInInjectionContext(() => Promise.all(getApps().map(app => deleteApp(app))));
117+
TestBed.resetTestingModule();
118+
});
119+
```
120+
121+
`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.
122+
123+
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.
124+
125+
## Replace AngularFire in the test
126+
127+
### Mock the module
128+
129+
*Applies to the modular API.*
130+
131+
The component imports `Auth` and `authState` from `@angular/fire/auth`. The test replaces the module with its own version of those two names.
132+
133+
#### Vitest example
134+
135+
```ts
136+
import { TestBed } from '@angular/core/testing';
137+
import { Auth, authState } from '@angular/fire/auth';
138+
import { firstValueFrom, of } from 'rxjs';
139+
import { UserBadge } from './user-badge';
140+
141+
vi.mock('@angular/fire/auth', () => ({
142+
Auth: class {},
143+
authState: vi.fn(() => of({ uid: 'user-1' })),
144+
}));
145+
146+
describe('UserBadge', () => {
147+
it('shows the signed-in user', () => {
148+
TestBed.configureTestingModule({ providers: [{ provide: Auth, useValue: {} }] });
149+
const component = TestBed.createComponent(UserBadge).componentInstance;
150+
151+
return firstValueFrom(component.user$).then(user => expect(user).toEqual({ uid: 'user-1' }));
152+
});
153+
154+
it('handles a signed-out visitor', () => {
155+
vi.mocked(authState).mockReturnValueOnce(of(null));
156+
TestBed.configureTestingModule({ providers: [{ provide: Auth, useValue: {} }] });
157+
const component = TestBed.createComponent(UserBadge).componentInstance;
158+
159+
return firstValueFrom(component.user$).then(user => expect(user).toBeNull());
160+
});
161+
});
162+
```
163+
164+
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`.
165+
166+
`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.
167+
168+
#### Keep `async` out of the spec file
169+
170+
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).
171+
172+
#### Turn on test isolation
173+
174+
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`.
175+
176+
With `@angular/build` 22, set `isolate` on the `test` target in `angular.json`:
177+
178+
```json
179+
"test": {
180+
"builder": "@angular/build:unit-test",
181+
"options": { "isolate": true }
182+
}
183+
```
184+
185+
`@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`:
186+
187+
```ts
188+
import { defineConfig } from 'vitest/config';
189+
190+
export default defineConfig({ test: { isolate: true } });
191+
```
192+
193+
With isolation on, every spec file loads its imports again, so the run takes longer.
194+
195+
#### Mock the package, not your own files
196+
197+
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.
198+
199+
#### Jest example
200+
201+
Write `jest` in place of `vi`. The tests stay as they are in the Vitest example.
202+
203+
```ts
204+
jest.mock('@angular/fire/auth', () => ({
205+
Auth: class {},
206+
authState: jest.fn(() => of({ uid: 'user-1' })),
207+
}));
208+
```
209+
210+
Jest needs none of the three Vitest notes above: it keeps spec files apart, accepts `async` tests, and can mock a relative import.
211+
212+
### Give `Auth` a fake object
213+
214+
*Applies to the modular API.*
215+
216+
The functions that read the signed-in state work with a small object in place of `Auth`. No module mock is needed.
217+
218+
```ts
219+
import { TestBed } from '@angular/core/testing';
220+
import { Auth } from '@angular/fire/auth';
221+
import { firstValueFrom } from 'rxjs';
222+
import { UserBadge } from './user-badge';
223+
224+
const fakeUser = { uid: 'user-1', getIdToken: () => Promise.resolve('token-1') };
225+
226+
const fakeAuth = {
227+
onAuthStateChanged: (next: (value: unknown) => void) => {
228+
next(fakeUser);
229+
return () => undefined;
230+
},
231+
onIdTokenChanged: (next: (value: unknown) => void) => {
232+
next(fakeUser);
233+
return () => undefined;
234+
},
235+
signOut: () => Promise.resolve(),
236+
};
237+
238+
it('shows the signed-in user', async () => {
239+
TestBed.configureTestingModule({ providers: [{ provide: Auth, useValue: fakeAuth }] });
240+
const component = TestBed.createComponent(UserBadge).componentInstance;
241+
242+
expect(await firstValueFrom(component.user$)).toEqual(fakeUser);
243+
});
244+
```
245+
246+
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+
248+
It is not enough for `signInWithEmailAndPassword`, which throws `authInstance._getRecaptchaConfig is not a function`. [Mock the module](#mock-the-module) for sign-in calls.
249+
250+
### Replace a compat service
251+
252+
*Applies to the compat API.*
253+
254+
Compat services are classes with methods and properties, so `TestBed` can replace one with an object:
255+
256+
```ts
257+
import { TestBed } from '@angular/core/testing';
258+
import { AngularFireAuth } from '@angular/fire/compat/auth';
259+
import { of } from 'rxjs';
260+
261+
TestBed.configureTestingModule({
262+
providers: [{ provide: AngularFireAuth, useValue: { authState: of({ uid: 'user-1' }) } }],
263+
});
264+
```
265+
266+
A component that injects `AngularFireAuth` then reads `{ uid: 'user-1' }` from `authState`.
267+
268+
## What does not work
269+
270+
### Spying on AngularFire functions
271+
272+
*Applies to the modular API.*
273+
274+
`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+
276+
Do this instead: [mock the module](#mock-the-module).
277+
278+
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+
280+
```ts
281+
import * as fireAuth from '@angular/fire/auth';
282+
import { of } from 'rxjs';
283+
284+
jest.mock('@angular/fire/auth', () => ({ __esModule: true, ...jest.requireActual('@angular/fire/auth') }));
285+
286+
it('shows the signed-out state', () => {
287+
const spy = jest.spyOn(fireAuth, 'authState').mockReturnValue(of(null));
288+
// ...
289+
});
290+
```
291+
292+
### Fake `Firestore` and `Storage` objects
293+
294+
*Applies to the modular API.*
295+
296+
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')`.
297+
298+
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.
299+
300+
### No Firebase App has been created
301+
302+
*Applies to the modular API.*
303+
304+
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:
305+
306+
- **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:
307+
- Create the app before creating the component, with `TestBed.runInInjectionContext(() => initializeApp(fakeOptions))`. Configure `TestBed` first, because it cannot be configured after this call.
308+
- Change the code to inject `Auth` or `Firestore`.
309+
- **The test imports `FirebaseAppModule` without providing an app.** Add `provideFirebaseApp(() => initializeApp(fakeOptions))`.
310+
- **The app was given a name.** `initializeApp(fakeOptions, 'name')` does not create the default app, so `provideAuth(() => getAuth())` cannot find one. Drop the name.
311+
312+
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.
313+
314+
### The compat `AngularFireAuth` with a real app
315+
316+
*Applies to the compat API.*
317+
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`.
319+
320+
Do this instead: [replace the compat service](#replace-a-compat-service).
321+
322+
### Keeping the real module with `importOriginal`
323+
324+
*Applies to the modular API.*
325+
326+
In Vitest a mock can also be built from the real module, to replace one function and keep the rest:
327+
328+
```ts
329+
vi.mock('@angular/fire/auth', async importOriginal => ({
330+
...(await importOriginal<typeof import('@angular/fire/auth')>()),
331+
authState: vi.fn(() => of({ uid: 'user-1' })),
332+
}));
333+
```
334+
335+
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).
336+
337+
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.
338+
339+
### `vi.mock` in an Angular 22 app that uses zone.js
340+
341+
*Applies to both APIs.*
342+
343+
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.
344+
345+
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`.
346+
347+
## Jest setup
348+
349+
With Jest 30 and the `jsdom` test environment, a test that imports `firebase/auth` or `@angular/fire/auth` fails before it runs:
350+
351+
```
352+
ReferenceError: fetch is not defined
353+
```
354+
355+
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`:
356+
357+
```js
358+
// jest.resolver.js
359+
const firebaseAuthPackages = ['@firebase/auth', '@firebase/auth/internal', '@firebase/auth-compat'];
360+
361+
module.exports = (request, options) => {
362+
const conditions = firebaseAuthPackages.includes(request) ? ['browser', 'require', 'default'] : options.conditions;
363+
return options.defaultResolver(request, { ...options, conditions });
364+
};
365+
```
366+
367+
Then reference the file in `jest.config.js`:
368+
369+
```js
370+
module.exports = {
371+
// the rest of your Jest configuration
372+
resolver: '<rootDir>/jest.resolver.js',
373+
};
374+
```
375+
376+
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.
377+
378+
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+
380+
## Moving from Jest to Vitest
381+
382+
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`.

0 commit comments

Comments
 (0)