vitest-auto-spy 5.8.0 → 5.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/AGENTS.md +613 -239
  2. package/README.md +206 -140
  3. package/dist/angular-http.js +2 -2
  4. package/dist/angular-router.d.ts +100 -2
  5. package/dist/angular-router.js +187 -3
  6. package/dist/angular.d.ts +339 -33
  7. package/dist/angular.js +466 -47
  8. package/dist/bun-angular.d.ts +5 -5
  9. package/dist/bun-angular.js +170 -24
  10. package/dist/bun.d.ts +5 -5
  11. package/dist/bun.js +9 -8
  12. package/dist/{chunk-KXV23662.js → chunk-BDJYPKLB.js} +2 -2
  13. package/dist/chunk-DTZCPCMA.js +89 -0
  14. package/dist/{chunk-UEG2I3VY.js → chunk-F334GPEI.js} +17 -11
  15. package/dist/{chunk-PSUX3M3P.js → chunk-FNOXP6VT.js} +1 -1
  16. package/dist/{chunk-OG6UKRFZ.js → chunk-GNJLDNJS.js} +1 -1
  17. package/dist/{chunk-ENI3G4RS.js → chunk-GZLFVXCY.js} +2 -2
  18. package/dist/{chunk-JIG2WCRH.js → chunk-HXH2QXK2.js} +2 -2
  19. package/dist/{chunk-NRVAJJKN.js → chunk-HZPV3CHD.js} +2 -2
  20. package/dist/{chunk-56WFZULJ.js → chunk-JOI3BLCL.js} +7 -6
  21. package/dist/{chunk-5PJOEE3N.js → chunk-M6VMOOZ2.js} +1 -1
  22. package/dist/{chunk-A7U5NBQK.js → chunk-N3T7KWWA.js} +2 -2
  23. package/dist/{chunk-PXYOVG56.js → chunk-NQNHA3R4.js} +3 -89
  24. package/dist/{chunk-B273FCFO.js → chunk-OTOCFH6B.js} +24 -24
  25. package/dist/{chunk-5ROGATP4.js → chunk-Q477VHHF.js} +1 -0
  26. package/dist/cli.js +1290 -264
  27. package/dist/console.d.ts +1 -1
  28. package/dist/console.js +6 -5
  29. package/dist/dom-stubs.d.ts +1 -1
  30. package/dist/eslint-plugin.cjs +303 -19
  31. package/dist/{expect-emission-BUdHCyYJ.d.ts → expect-emission-CmN9ADyN.d.ts} +1 -1
  32. package/dist/index.d.ts +4 -4
  33. package/dist/index.js +13 -7
  34. package/dist/jasmine-compat.d.ts +1 -1
  35. package/dist/jasmine.d.ts +2 -2
  36. package/dist/jasmine.js +9 -8
  37. package/dist/nestjs.d.ts +2 -2
  38. package/dist/nestjs.js +10 -9
  39. package/dist/node.cjs +13 -7
  40. package/dist/node.d.ts +4 -4
  41. package/dist/node.js +8 -8
  42. package/dist/{package-identity-DDylC3ri.d.ts → package-identity-lm-gqZAR.d.ts} +1 -1
  43. package/dist/perf-reporter.js +46 -3
  44. package/dist/{prop-mock-sa1PC4xj.d.ts → prop-mock-DnYNBNJL.d.ts} +1 -1
  45. package/dist/react.d.ts +4 -4
  46. package/dist/react.js +10 -9
  47. package/dist/rstest.d.ts +4 -4
  48. package/dist/rstest.js +9 -9
  49. package/dist/rxjs.d.ts +2 -2
  50. package/dist/rxjs.js +2 -2
  51. package/dist/setup.d.ts +3 -3
  52. package/dist/setup.js +10 -9
  53. package/dist/signal-forms.d.ts +83 -0
  54. package/dist/signal-forms.js +101 -0
  55. package/dist/svelte.d.ts +4 -4
  56. package/dist/svelte.js +10 -9
  57. package/dist/{track-injections-D1KdfjXr.d.ts → track-injections-CIHJWFpp.d.ts} +1 -1
  58. package/dist/{zoneless-CBxpxspb.d.ts → track-signal-runs-BoA6j-74.d.ts} +181 -54
  59. package/dist/{types-CrmNZKfd.d.ts → types-D3RkJjc_.d.ts} +1 -1
  60. package/dist/vue.d.ts +5 -5
  61. package/dist/vue.js +11 -10
  62. package/package.json +13 -3
  63. package/skills/vitest-auto-spy/SKILL.md +122 -91
package/AGENTS.md CHANGED
@@ -52,18 +52,19 @@ adapter installed and spies fail at runtime.
52
52
 
53
53
  Add-ons, orthogonal to the runner:
54
54
 
55
- | Add-on | Import | Needed for |
56
- | ----------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
57
- | Observable spies | `import 'vitest-auto-spy/rxjs'` | `nextWith` & friends. **Side-effect import, once**, and in a file the `tsconfig` includes (§4) |
58
- | observer-spy shim | `vitest-auto-spy/observer-spy` | `subscribeSpyTo` — the `@hirez_io/observer-spy` surface (§20). Its own entry so `/rxjs` does not carry it |
59
- | Console spies | `vitest-auto-spy/console` | silent typed spies over the global `console` — `installConsoleSpies()` per test, `restoreConsole()` after |
60
- | DOM stubs | `vitest-auto-spy/dom-stubs` | `stubIntersectionObserver` / `stubResizeObserver` / `stubMutationObserver` / `stubObserver`, `stubMediaElement`, `stubAbortController`, `stubWebStorage` (§12), `intersectionEntry` / `resizeEntry` / `mutationRecord`. **Moved off the root in 4.0.0** |
61
- | Run diagnostics | `vitest-auto-spy/diagnostics` | `compareTestRuns`, `summarizeTestRun`, `formatTestRunComparison`, `diffByField`. **Moved off the root in 4.0.0** |
62
- | Angular HTTP | `vitest-auto-spy/angular-http` | `provideHttpTesting`, `expectRequest` — `httpResource()` / `HttpClient` (§13). Optional `@angular/common` peer, this entry only |
63
- | Angular router | `vitest-auto-spy/angular-router` | `provideActivatedRoute`, `injectActivatedRoute` — an `ActivatedRoute` whose streams and snapshot share one record (§13). Optional `@angular/router` peer, this entry only |
64
- | Setup helpers | `vitest-auto-spy/setup` | `setupAutoSpy()`, `setupFakeTimers()` |
65
- | Zone patch | `import 'vitest-auto-spy/zone'` | `fakeAsync` / `waitForAsync` on Vitest (§14) |
66
- | jasmine compat | `vitest-auto-spy/jasmine` | `.and` / `.calls` / `.withArgs`, the `jasmine` namespace (§20) |
55
+ | Add-on | Import | Needed for |
56
+ | ----------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
57
+ | Observable spies | `import 'vitest-auto-spy/rxjs'` | `nextWith` & friends. **Side-effect import, once**, and in a file the `tsconfig` includes (§4) |
58
+ | observer-spy shim | `vitest-auto-spy/observer-spy` | `subscribeSpyTo` — the `@hirez_io/observer-spy` surface (§20). Its own entry so `/rxjs` does not carry it |
59
+ | Console spies | `vitest-auto-spy/console` | silent typed spies over the global `console` — `installConsoleSpies()` per test, `restoreConsole()` after |
60
+ | DOM stubs | `vitest-auto-spy/dom-stubs` | `stubIntersectionObserver` / `stubResizeObserver` / `stubMutationObserver` / `stubObserver`, `stubMediaElement`, `stubAbortController`, `stubWebStorage` (§12), `intersectionEntry` / `resizeEntry` / `mutationRecord`. **Moved off the root in 4.0.0** |
61
+ | Run diagnostics | `vitest-auto-spy/diagnostics` | `compareTestRuns`, `summarizeTestRun`, `formatTestRunComparison`, `diffByField`. **Moved off the root in 4.0.0** |
62
+ | Angular HTTP | `vitest-auto-spy/angular-http` | `provideHttpTesting`, `expectRequest` — `httpResource()` / `HttpClient` (§13). Optional `@angular/common` peer, this entry only |
63
+ | Angular router | `vitest-auto-spy/angular-router` | `provideActivatedRoute`, `injectActivatedRoute` — an `ActivatedRoute` whose streams and snapshot share one record; `provideRouterDouble`, `injectRouterDouble` — a `Router` whose URL, `routerState` and `events` agree (§13). Optional `@angular/router` peer, this entry only |
64
+ | Signal forms | `vitest-auto-spy/signal-forms` | `createForm`, `registerFormMatchers` — a signal form built where `form()` can inject, and `toHaveFieldErrors` over what it produced (§13). Optional `@angular/forms` peer, this entry only; Angular 22+ |
65
+ | Setup helpers | `vitest-auto-spy/setup` | `setupAutoSpy()`, `setupFakeTimers()` |
66
+ | Zone patch | `import 'vitest-auto-spy/zone'` | `fakeAsync` / `waitForAsync` on Vitest (§14) |
67
+ | jasmine compat | `vitest-auto-spy/jasmine` | `.and` / `.calls` / `.withArgs`, the `jasmine` namespace (§20) |
67
68
 
68
69
  `vitest-auto-spy/jasmine` is Vitest-only, because it registers the Vitest adapter. On `bun test` and
69
70
  `node --test` call `enableJasmineCompat()` from `vitest-auto-spy/jasmine-compat` instead.
@@ -606,7 +607,9 @@ would then take the wrong branch, silently, which is the exact failure mode the
606
607
  in §2 exists to remove. A loud `TypeError` on the spec's own line is the better of the two.
607
608
 
608
609
  For an ngrx `signalStore()`, prefer `createAutoMock<T>()` over listing every member: it mocks from
609
- the type, needs no prototype, and the list cannot fall behind the store.
610
+ the type, needs no prototype, and the list cannot fall behind the store. Its **signal** members want
611
+ `mockSignalProp`, not a method spy — a store's state is read during the first render, so a method spy
612
+ there answers `undefined` to the template.
610
613
 
611
614
  The symptom of getting this wrong is **a spy that is never called and no warning at all**: the
612
615
  additive lists exist precisely to name things the prototype does not have, so a typo in one cannot
@@ -785,7 +788,7 @@ Precedence, first one set wins: the double's `onUnstubbedCall` → the double's
785
788
  `mockImplementation`, `overrides: { x }` (call site or registration — a registered _list_ alone is
786
789
  not), `mockReadonlyProp`; for a stream any of `nextWith` / `throwWith` / `complete` /
787
790
  `returnSubject`. `undefined` meant: `mockReturnValue(undefined)`. `onUnstubbedRead({ className,
788
- member, kind, count })` — suite-wide or per double, same precedence as `onUnstubbedCall` — takes the
791
+ member, kind, count })` — suite-wide or per double, same precedence as `onUnstubbedCall` — takes the
789
792
  findings instead of the report, from every double not `strict: false`: survey with it first.
790
793
  - **Angular lifecycle hooks are exempt.** `ngOnDestroy`, `ngOnInit`, `ngOnChanges`, `ngDoCheck` and the
791
794
  `ngAfter…` hooks answer `undefined` on a strict double: Angular calls `ngOnDestroy` itself on every
@@ -879,8 +882,10 @@ It applies to `createSpyFromClass` with a configuration too, in one combination:
879
882
  after the configuration, reads `T` back from `gettersToSpyOn: ['remoteConfig']` as
880
883
  `{ remoteConfig: any }`, and fails with `'isKeyEnabled' does not exist in type
881
884
  'MethodReturns<{ remoteConfig: any; }>'`. Spell it out — `createSpyFromClass<RemoteConfigService>(…)`.
882
- `provideAutoSpy`, `overrideAutoSpy` and `overrideComponentProvider` (`/angular`) take `T` from the
883
- class alone, so there the inferred form compiles.
885
+ `provideAutoSpy`, `overrideAutoSpy`, `overrideComponentProvider` and the class overload of
886
+ `registerAutoSpyDefaults` (`/angular`) take `T` from the class alone, so there the inferred form
887
+ compiles; the core `registerAutoSpyDefaults` needs the argument spelled out like
888
+ `createSpyFromClass`. A token key needs nothing: `T` comes from the `InjectionToken<T>` itself.
884
889
 
885
890
  **A declared default now reaches the double, and used not to.** `class RemoteConfigService<T =
886
891
  RemoteConfigDefaults>` handed to `createSpyFromClass` / `injectSpy` inferred `T` as `unknown`, so
@@ -1726,7 +1731,7 @@ never holds fails naming the `label` rather than hanging until the runner's time
1726
1731
 
1727
1732
  **Not for an Angular `resource()` / `httpResource()`.** Those need a change-detection _tick_, and
1728
1733
  this helper only takes event-loop turns — a resource awaited through it finishes the whole budget
1729
- having issued zero requests. `settleResource(resource, { turns, label })` from
1734
+ having issued zero requests. `settleResource(resource, { turns, label, allowIdle })` from
1730
1735
  `vitest-auto-spy/angular` is that wait.
1731
1736
 
1732
1737
  `flushEventLoop(turns?)` takes real event-loop turns even while the timers are faked, without
@@ -1808,7 +1813,7 @@ for this test — `getItem` / `setItem` / `removeItem` / `clear` / `key` / `leng
1808
1813
  as the platform does it — and `snapshot()` is the plain record to assert on:
1809
1814
 
1810
1815
  ```ts
1811
- import { stubWebStorage, type WebStorageStub } from 'vitest-auto-spy/dom-stubs';
1816
+ import { type WebStorageStub, stubWebStorage } from 'vitest-auto-spy/dom-stubs';
1812
1817
 
1813
1818
  let local: WebStorageStub;
1814
1819
 
@@ -1937,6 +1942,12 @@ statement is not brevity: the shortcut people take instead is an exported `const
1937
1942
  the values, and under `isolate: false` that is one set of spies shared by every file that imports
1938
1943
  it.
1939
1944
 
1945
+ **A member named in both wins as the seed**, whatever the seed is — a value, a plain function, a
1946
+ `vi.fn()`. `returns` and `selfReturning` skip such a member rather than configuring it, which is the
1947
+ precedence the merge already applies between a registration and a call site: a spec seeding `channel`
1948
+ over `registerAutoSpyDefaults(LOGGER, { selfReturning: ['channel'] })` gets its own function back, not
1949
+ the registered link.
1950
+
1940
1951
  **`observablePropsToSpyOn` works on a token too**, and matters more there than on a class. A class
1941
1952
  tells the factory which members are methods; a type does not, so _every_ unnamed key of a
1942
1953
  token-driven double is a function spy — including an `Observable` property, which the code under
@@ -1998,6 +2009,25 @@ selected.set(true); // every computed reading it updates
1998
2009
  Use it whenever the value has to change during the test. `mockReadonlyProp` stays right when the
1999
2010
  value is fixed for the whole test and you never need the handle.
2000
2011
 
2012
+ A `linkedSignal()` is a writable signal like any other, so `mockSignalProp` covers it and there is
2013
+ no separate helper to go looking for.
2014
+
2015
+ **It patches as little as it can, and the order rule follows from that.** A member that is already
2016
+ writable — `signal()`, `model()`, `linkedSignal()` — is **written through**, not replaced: Angular
2017
+ links a consumer to the signal it read, not to the property it read it through, so replacing one
2018
+ that anything has already read strands every `computed()`, `effect()` and template binding on the
2019
+ old signal, silently and for the rest of the test. Writing through keeps all of them, keeps a
2020
+ `model()`'s output half alive, and leaves nothing for `restoreMockedProps()` to undo — the value
2021
+ stays where the spec left it.
2022
+
2023
+ Two shapes are still swapped: a `computed()` the class declares, and a member the spy does not have
2024
+ yet. **Patch those before anything reads them** — before the first `detectChanges()` /
2025
+ `stable(fixture)`. A read-only signal a live consumer has already read is refused by name rather
2026
+ than replaced where nothing would notice it, and an `input()` is refused outright: Angular sets an
2027
+ input through the input node rather than the property, so a replaced one breaks the host's next
2028
+ write. Drive an input with `fixture.componentRef.setInput(name, value)`, or with
2029
+ `renderShallow(Component, { inputs: { … } })` for the value it starts at.
2030
+
2001
2031
  ### Observers the component constructs itself
2002
2032
 
2003
2033
  Do not assign `globalThis.IntersectionObserver` by hand: it stays assigned, and under
@@ -2272,11 +2302,11 @@ is `undefined` on the `{ params: of(…) }` one, and a spec that updates one hal
2272
2302
  no navigation produces. `provideActivatedRoute(init)` provides **Angular's own `ActivatedRoute`**
2273
2303
  built over one record, so every stream, both `ParamMap`s and `snapshot` read the same values.
2274
2304
 
2275
- | Call | Does |
2276
- | -------------------------------------- | ------------------------------------------------------------------------------------------------------ |
2277
- | `provideActivatedRoute(init?)` | a `FactoryProvider` — a fresh route per injector; `init`: `params`, `queryParams`, `data`, `fragment`, `url`, `outlet`, `component`, `routeConfig` |
2278
- | `injectActivatedRoute(injector?)` | the handle: `.route`, `setParams`, `setQueryParams`, `setData`, `setFragment`, `setUrl`, `set({ … })` |
2279
- | `createActivatedRoute(init?)` | the same handle without a `TestBed` — for `new Page(route)`, or a guard given `route.snapshot` |
2305
+ | Call | Does |
2306
+ | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
2307
+ | `provideActivatedRoute(init?)` | a `FactoryProvider` — a fresh route per injector; `init`: `params`, `queryParams`, `data`, `fragment`, `url`, `outlet`, `component`, `routeConfig` |
2308
+ | `injectActivatedRoute(injector?)` | the handle: `.route`, `setParams`, `setQueryParams`, `setData`, `setFragment`, `setUrl`, `set({ … })` |
2309
+ | `createActivatedRoute(init?)` | the same handle without a `TestBed` — for `new Page(route)`, or a guard given `route.snapshot` |
2280
2310
 
2281
2311
  A setter behaves like the router after a navigation: it **replaces** (not merges) that part, builds
2282
2312
  a new snapshot first, then emits only the streams whose value changed (router equality: same keys,
@@ -2296,6 +2326,250 @@ Four things to know:
2296
2326
  - **Its own entry, like `/angular-http`.** It does not re-export the core, imports no runner, and is
2297
2327
  the only file that reaches `@angular/router` — an optional peer.
2298
2328
 
2329
+ ### `Router` from one URL — `vitest-auto-spy/angular-router`
2330
+
2331
+ ```ts
2332
+ import { injectRouterDouble, provideRouterDouble } from 'vitest-auto-spy/angular-router';
2333
+
2334
+ TestBed.configureTestingModule({ providers: [provideRouterDouble({ url: '/products/7' })] });
2335
+
2336
+ const router = injectRouterDouble();
2337
+
2338
+ router.emitNavigation('/products/8'); // events emits a NavigationEnd; router.url already reads it
2339
+ expect(router.navigate).toHaveBeenCalledWith(['/checkout']);
2340
+ ```
2341
+
2342
+ **Do not hand-write `createAutoMock<Router>({ events: of(), url: '/' }, { returns: { navigate:
2343
+ Promise.resolve(true) } })`** — the line 48 hand-rolled providers across two private suites all
2344
+ converged on, and every part of it is a guess the component falls through: `of()` never emits again,
2345
+ `url` is a string nobody updates, `routerState` is absent, `serializeUrl` throws on the first
2346
+ redirect a guard builds. `provideRouterDouble(init)` keeps one URL and derives the rest.
2347
+
2348
+ | Call | Does |
2349
+ | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
2350
+ | `provideRouterDouble(init?)` | a `FactoryProvider` for the `Router` token — a fresh router per injector; `init` is `{ url }`, default `'/'` |
2351
+ | `injectRouterDouble(injector?)` | the handle: `.router`, `.navigate`, `.navigateByUrl`, `setUrl(url)`, `emitNavigation(event?)`, `setCurrentNavigation(navigation?)` |
2352
+ | `createRouterDouble(init?)` | the same handle without a `TestBed` — for `new AuthGuard(router)` |
2353
+
2354
+ Unlike the route, this is **not** an instance of Angular's class: a real `Router` drags the whole
2355
+ routing stack in. It is a structural double that answers `url` (serialized as the real router does),
2356
+ `events` (a `BehaviorSubject` starting at the `NavigationEnd` that put it there), `navigate` and
2357
+ `navigateByUrl` (spies resolving `true`), `serializeUrl` / `parseUrl` / `createUrlTree` (the
2358
+ router's own URL work, via `DefaultUrlSerializer` and `createUrlTreeFromSnapshot`), `routerState`
2359
+ (Angular's own, its `snapshot.url` the URL) and `currentNavigation` / `getCurrentNavigation()` (the
2360
+ navigation in flight, `null` while the router stands still). **Every other member `Router` declares
2361
+ throws by name** rather than reading `undefined` — and that holds for the instance fields too, which
2362
+ is why a hand-rolled double needs `instanceMethodsToSpyOn: ['currentNavigation']` and this one does
2363
+ not.
2364
+
2365
+ Five things to know:
2366
+
2367
+ - **It does not navigate.** `navigate()` records the call and resolves `true`; it does not move
2368
+ `url`. `setUrl()` and `emitNavigation()` move it; `RouterTestingHarness` over a real
2369
+ `provideRouter()` is what tests a navigation.
2370
+ - **`emitNavigation()` takes what you have** — nothing, a URL string, or an event you built. A
2371
+ `NavigationEnd` moves the URL with it; any other event does not.
2372
+ - **The navigation in flight follows the events.** `setCurrentNavigation({ extras: { state } })`
2373
+ puts one up and `setCurrentNavigation(null)` ends it; a `NavigationStart` pushed through
2374
+ `emitNavigation()` starts one with that event's id, URL and trigger, and a `NavigationEnd`,
2375
+ `NavigationCancel`, `NavigationError` or `NavigationSkipped` drops it back to `null` — which is
2376
+ what the real router answers to a component reading it while handling a `NavigationEnd`.
2377
+ - **Ordering does not matter here.** `Router` is `providedIn: 'root'` and `provideRouter()` does not
2378
+ re-provide the token, so the double wins in either order — and a `TestBed` without it hands out a
2379
+ real router, which is what `injectRouterDouble()` says by name.
2380
+ - **It builds spies**, so a runtime entry has to be imported in the suite (`vitest-auto-spy/angular`
2381
+ in the same file, or the setup file); the route double needs none.
2382
+
2383
+ ### Signal forms — `vitest-auto-spy/signal-forms`
2384
+
2385
+ ```ts
2386
+ import { minLength, required } from '@angular/forms/signals';
2387
+ import { createForm, registerFormMatchers } from 'vitest-auto-spy/signal-forms';
2388
+
2389
+ registerFormMatchers(); // once, in the setup file
2390
+
2391
+ const user = createForm({ email: '', name: '' }, (path) => {
2392
+ required(path.email, { message: 'Email is required' });
2393
+ minLength(path.name, 2);
2394
+ });
2395
+
2396
+ expect(user.email).toHaveFieldErrors([{ kind: 'required', message: 'Email is required' }]);
2397
+
2398
+ user.email().value.set('ada@example.test');
2399
+
2400
+ expect(user.email).toHaveFieldErrors([]);
2401
+ ```
2402
+
2403
+ Signal forms are stable from Angular 22, and a spec that touches one meets the same two things every
2404
+ time. **`form()` injects**, so a call in a `beforeEach` throws `NG0203: The Injector token injection
2405
+ failed` — a message about `inject()` that never says "form", whose repair is
2406
+ `{ injector: TestBed.inject(Injector) }` or a `TestBed.runInInjectionContext` around the call.
2407
+ **`errors()` answers `RequiredValidationError` instances**, each carrying a `fieldTree`
2408
+ back-reference, so `toEqual([{ kind: 'required' }])` fails on a property nobody wrote and every
2409
+ suite falls back to `errors().some((error) => error.kind === 'required')` — which passes just as
2410
+ happily when the field has three other errors nobody expected.
2411
+
2412
+ | Call | Does |
2413
+ | --------------------------------------------- | ------------------------------------------------------------------------- |
2414
+ | `createForm(model, schema?, options?)` | Angular's own `form()`, built in the `TestBed`'s injection context |
2415
+ | `createForm(initialValue, schema?, options?)` | the same, with the model signal made for you |
2416
+ | `registerFormMatchers()` | adds `expect(field).toHaveFieldErrors(kinds)` — the whole set, order-free |
2417
+
2418
+ Four things to know:
2419
+
2420
+ - **What comes back is Angular's `FieldTree`**, not a double: the states, the validators and the
2421
+ write-through to the model are the framework's. A spec that passes its own `signal()` asserts on it
2422
+ directly; a plain value gets a signal made here, and `user().value()` reads it back either way.
2423
+ - **A `computed()` is refused by name** — a form writes into its model, and without the check a
2424
+ derived signal would be wrapped as a value while every write vanished.
2425
+ - **`options.injector` is for the validator that injects**: pass `fixture.debugElement.injector`
2426
+ when the service a schema reaches for lives in a component's own `providers`.
2427
+ - **`toHaveFieldErrors` compares the whole set**, by `kind`, and by `message` only where the spec
2428
+ names one; `[]` is "no errors". A field tree and its state both read, so `expect(user.email)` and
2429
+ `expect(user.email())` are the same assertion.
2430
+
2431
+ **No `FieldTree` double is shipped, on purpose.** It would stand in for a form a component takes as
2432
+ an input, and across the measured suites no component takes one: forms are built by the component
2433
+ that owns them (assert through `component.form.tags()`), and custom controls — `FormValueControl<T>`,
2434
+ `FormCheckboxControl` — are plain components whose contract is `value = model<T>()`, which is
2435
+ `renderShallow` plus `setInputs`.
2436
+
2437
+ ### `window` and `document` over the real ones — `provideWindowDouble` / `provideDocumentDouble`
2438
+
2439
+ ```ts
2440
+ import { provideDocumentDouble, provideWindowDouble } from 'vitest-auto-spy/angular';
2441
+
2442
+ TestBed.configureTestingModule({
2443
+ providers: [
2444
+ provideWindowDouble(WINDOW, { screen: { width: 1920, height: 1080 }, devicePixelRatio: 2 }),
2445
+ provideDocumentDouble({ visibilityState: 'hidden' }),
2446
+ ],
2447
+ });
2448
+ ```
2449
+
2450
+ **Do not write `useValue: window`, and do not build a `mockDocument` from scratch.** These are the
2451
+ two most hand-rolled providers in an Angular suite — 95 `window` ones and 70 `document` ones across
2452
+ two private suites — and both hand-written shapes fail the same way. `useValue: window` isolates
2453
+ nothing: what the test writes stays on the global for the rest of the worker. A double built from
2454
+ scratch, whether a slice (`{ screen: { width: 1280, height: 720 } }`) or a `mockDocument` with one
2455
+ hand-written `querySelector`, knows only the members its author thought of, so the component that
2456
+ reads `screen.colorDepth` or calls `document.createElement` gets `undefined` and the spec fails
2457
+ somewhere unrelated to what it was testing.
2458
+
2459
+ These two merge the overrides **over the real jsdom object** instead: everything the spec did not
2460
+ name — `location.href`, `getComputedStyle`, `addEventListener`, `document.createElement` — still
2461
+ answers the way jsdom answers it.
2462
+
2463
+ | Call | Does |
2464
+ | --------------------------------------------------------------------- | ----------------------------------------------------------------- |
2465
+ | `provideWindowDouble(token, overrides?)` | a `FactoryProvider` under the application's own window token |
2466
+ | `provideDocumentDouble(overrides?, token?)` | the same under Angular's `DOCUMENT`, or under a token of your own |
2467
+ | `createWindowDouble(overrides?)` / `createDocumentDouble(overrides?)` | the same doubles without a `TestBed` |
2468
+
2469
+ Five things to know:
2470
+
2471
+ - **The window helper needs your token.** Angular ships `DOCUMENT` (from `@angular/core` itself
2472
+ since v20) and has never shipped a `WINDOW`: every application declares its own
2473
+ `InjectionToken<Window>`. The helper is generic over the token's type, so an
2474
+ `InjectionToken<AppWindow>` has that interface's members checked in the overrides too.
2475
+ - **A plain `{ … }` merges, anything else replaces.** `{ screen: { width: 1920 } }` keeps
2476
+ `screen.colorDepth`; a `vi.fn()`, an array, a `URL` or a stub instance becomes the member whole. The
2477
+ slice goes three levels down, the way the merge does — `{ document: { location: { href: '' } } }` is
2478
+ checked and merged member by member.
2479
+ - **Nothing to restore.** The globals are never patched — the double is a view over them, and every
2480
+ write and delete lands on the view, which is also how a spec moves a value mid-test:
2481
+ `Object.assign(TestBed.inject(WINDOW), { scrollY: 40 })` (`Object.assign` because lib.dom declares
2482
+ most of `Window` `readonly`). There is no handle and no `restoreMockedProps()` in this recipe.
2483
+ - **`provideDocumentDouble` hands the double to Angular as well** — the renderer injects `DOCUMENT`
2484
+ too, so replace `createElement` or `body` only where the spec means to.
2485
+ - **`location` takes overrides like everything else**, though the platform declares its members
2486
+ unforgeable: `{ location: { reload: vi.fn() } }` — the shape most hand-written window mocks are —
2487
+ records the reload, leaves `location.href` real, and `win.location.href = '/next'` moves the
2488
+ double rather than the address bar. `mockValueProp(TestBed.inject(WINDOW), 'innerWidth', 800)` and
2489
+ its restore work on the double too, and neither touches the global.
2490
+
2491
+ ### The Material dialog trio — `provideMatDialogData` / `provideMatDialogRef`
2492
+
2493
+ ```ts
2494
+ import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
2495
+ import { expectEmission, injectMatDialogRef, provideMatDialogData, provideMatDialogRef } from 'vitest-auto-spy/angular';
2496
+
2497
+ TestBed.configureTestingModule({
2498
+ providers: [provideMatDialogData<EditUserData>(MAT_DIALOG_DATA, { id: 7, name: 'Ada' }), provideMatDialogRef(MatDialogRef)],
2499
+ });
2500
+
2501
+ const dialog = injectMatDialogRef(MatDialogRef);
2502
+
2503
+ TestBed.createComponent(EditUserDialog).componentInstance.save();
2504
+
2505
+ expect(dialog.close).toHaveBeenCalledWith('saved');
2506
+ await expect(expectEmission(dialog.ref.afterClosed())).resolves.toBe('saved');
2507
+ ```
2508
+
2509
+ **`@angular/material` is not a dependency of this package and must not become one** — it ships no
2510
+ runtime dependencies at all. That is exactly why the token and the ref class are **arguments**:
2511
+ `MatDialogRef` is the DI token, the shape the double is measured against and the type the result is
2512
+ read off, so the spec's own Material import stays the only place it is named.
2513
+
2514
+ **Do not hand-roll `{ close: vi.fn() }`.** 36 of these across two private suites are the same three
2515
+ shapes, and the ref one fails twice. `close` is the only member anybody writes, so a component that
2516
+ subscribes to `afterClosed()` dies on "is not a function"; the repair written next to it,
2517
+ `afterClosed: () => of('saved')`, answers before anything closed the dialog — the spec then passes
2518
+ whether or not `close()` was ever called.
2519
+
2520
+ | Call | Does |
2521
+ | ----------------------------------------- | --------------------------------------------------------------------------------------------------------- |
2522
+ | `provideMatDialogData(token, data)` | a typed `{ provide, useValue }` — name the type argument and the data is checked against it |
2523
+ | `provideMatDialogRef(RefClass, init?)` | a `FactoryProvider` — a fresh ref per injector; `init`: `closedWith`, `disableClose`, `componentInstance` |
2524
+ | `injectMatDialogRef(RefClass, injector?)` | the handle: `.ref`, `.close` (the spy), `emitClose(result?)` |
2525
+ | `createMatDialogRef(RefClass, init?)` | the same handle without a `TestBed` — and the ref a spied `MatDialog.open()` hands back |
2526
+
2527
+ `MatDialog` itself needs no helper of its own: `provideAutoSpy(MatDialog)` already spies it, and the
2528
+ ref double is the thing its `open()` was missing.
2529
+
2530
+ ```ts
2531
+ TestBed.configureTestingModule({ providers: [provideAutoSpy(MatDialog)] });
2532
+
2533
+ injectSpy(MatDialog).open.mockReturnValue(createMatDialogRef(MatDialogRef, { closedWith: 'saved' }).ref);
2534
+ ```
2535
+
2536
+ Five things to know:
2537
+
2538
+ - **`close` is the spy, and it is the same function the ref carries.** `expect(dialog.close)` and
2539
+ `expect(TestBed.inject(MatDialogRef).close)` are one assertion. `emitClose(result?)` is the other
2540
+ half — the user closing the dialog from outside, where the streams move and the spy records
2541
+ nothing, and the only way to close with `undefined` (a dismissal), which `closedWith` cannot say.
2542
+ - **`afterClosed()` is replayed, where Material's is a plain `Subject`.** The deliberate departure:
2543
+ in a spec the assertion usually subscribes _after_ the component has closed the dialog, and a
2544
+ `Subject` has nothing left to say by then. `beforeClosed()` is the same stream — the double closes
2545
+ instantly, so there is no window between them, and `afterOpened()` has already emitted.
2546
+ - **`MAT_DIALOG_DATA` is `InjectionToken<any>` in Material**, so a hand-written `useValue: null`
2547
+ compiles for a component that reads `data.name`. `provideMatDialogData<EditUserData>(…)` checks the
2548
+ object; a token of your own typed `InjectionToken<EditUserData>` checks it without naming anything.
2549
+ The value is handed out as it is, so build it per test rather than hoisting it to a constant.
2550
+ - **`componentInstance` is how the opener drives the dialog**, and it is the one member Material
2551
+ keeps off the prototype, so a double that did not have it would read `undefined` rather than
2552
+ fail. Hand the stand-in over and the opener works against it — checked, member by member, against
2553
+ the component the ref class names:
2554
+
2555
+ ```ts
2556
+ const save = new EventEmitter<string>();
2557
+ const dialog = createMatDialogRef<MatDialogRef<NameInputDialog, string>>(MatDialogRef, {
2558
+ componentInstance: { save, isSaving: signal(false) },
2559
+ });
2560
+
2561
+ injectSpy(MatDialog).open.mockReturnValue(dialog.ref);
2562
+ save.emit('Grace');
2563
+
2564
+ expect(dialog.close).toHaveBeenCalledWith('Grace');
2565
+ ```
2566
+
2567
+ - **What it does not answer throws by name.** `backdropClick`, `keydownEvents`, `updateSize`,
2568
+ `updatePosition`, `getState`, `componentRef` and `id` are the dialog doing its own work; the
2569
+ double names them in the failure instead of reading `undefined`, and the real `MatDialogModule` is
2570
+ what answers them. A `componentInstance` nobody handed over says so by name too, and names the
2571
+ init field that fixes it.
2572
+
2299
2573
  ### Which collaborators the code asked for — `trackInjections`
2300
2574
 
2301
2575
  Do **not** reach for `vi.mock('@app/services')` to answer "was this collaborator used". Register the
@@ -2352,8 +2626,41 @@ runEffect(component.highlightEffect); // runs the body now, with the current sig
2352
2626
  ```
2353
2627
 
2354
2628
  `flushEffects()` runs everything currently dirty; `runEffect(ref)` runs one specific effect
2355
- regardless. Prefer asserting the result where practical — `runEffect` reads Angular's reactive node,
2356
- and throws with instructions if a future version moves it.
2629
+ regardless. It runs the previous run's cleanup first, the way Angular's own scheduler does, so an
2630
+ `onCleanup` callback is observable and the node does not collect one closure per call. An effect
2631
+ whose view has been torn down — or which was destroyed on its own — is refused rather than run:
2632
+ after `fixture.destroy()` there is nothing production could still produce. Prefer asserting the
2633
+ result where practical — `runEffect` reads Angular's reactive node, and throws with instructions if
2634
+ a future version moves it.
2635
+
2636
+ ### Counting recomputations and effect runs — `trackRecomputations` / `trackEffectRuns`
2637
+
2638
+ "The template read `total()` six times and the computation ran once" and "changing the filter did
2639
+ not re-run the sync effect" are not observable from the outside: a `computed()` returns the same
2640
+ value whether it was cached or recomputed. The usual workaround is a counter inside the computation,
2641
+ which means editing production code to make a test possible.
2642
+
2643
+ ```ts
2644
+ import { trackEffectRuns, trackRecomputations } from 'vitest-auto-spy/angular';
2645
+
2646
+ const recomputed = trackRecomputations(component.total);
2647
+ const synced = trackEffectRuns(component.syncEffect);
2648
+
2649
+ component.unrelatedFilter.set('open');
2650
+ await stable(fixture);
2651
+
2652
+ expect(component.total()).toBe(42);
2653
+ expect(recomputed.count).toBe(0); // memoised: nothing it reads changed
2654
+ expect(synced.count).toBe(0);
2655
+
2656
+ recomputed.stop(); // and `restoreMockedProps()` — so `setupAutoSpy()` — takes both off anyway
2657
+ ```
2658
+
2659
+ Both return `{ count, stop() }`. `trackRecomputations` counts the **computation**, not the reads,
2660
+ and takes a `computed()` or a `linkedSignal()` — a plain `signal()` has nothing to compute and is
2661
+ refused by name. `trackEffectRuns` counts every run whoever asked for it: a flush, a `stable()`, a
2662
+ `runEffect()` of the same effect. Both wrap one member of Angular's reactive node through
2663
+ `mockValueProp`, so the undo is the journal every other stub in this package uses.
2357
2664
 
2358
2665
  ### ngrx `rxMethod`
2359
2666
 
@@ -2372,6 +2679,10 @@ const { fixture, component } = renderShallow(TaskListComponent, {
2372
2679
  });
2373
2680
  // other options: imports, keepTemplate, keepChildren, template, beforeCreate, detectChanges
2374
2681
 
2682
+ // change an input after the first render — one setInput per key, then the wait, in one await
2683
+ await setInputs(fixture, { projectId: 7 }); // a name the component does not declare is refused here
2684
+ await setInputs(fixture, { projectId: 7 }, { label: 'the task list' }); // options go to stable()
2685
+
2375
2686
  // build a class through DI, every unprovided token auto-spied
2376
2687
  const { instance, spies } = createWithAutoSpies(CartService, {
2377
2688
  providers: [{ provide: TaxService, useValue: realTax }], // explicit providers win
@@ -2388,11 +2699,20 @@ flushEffects(); // the no-fixture half: services, stores, runInInjectionContext
2388
2699
  flushEffects(); // an httpResource issues NO request until something ticks
2389
2700
  httpTesting.expectOne('/api/products').flush([product]);
2390
2701
  await settleResource(products, { label: 'the product resource' });
2702
+ // a resource left 'idle' FAILS here — params() returned undefined and value() is still the default;
2703
+ // { allowIdle: true } when that is the state under assertion, { turns } is spent exactly as reported
2704
+
2705
+ // on a component the resource is a FIELD and renderShallow is the injection context — nothing else changes
2706
+ const { component } = renderShallow(ProductListComponent, { providers: [...provideHttpTesting()], keepTemplate: true });
2707
+ await expectRequest('/api/products?q=').flush([product]); // both from /angular-http; renderShallow already ticked
2708
+ expect(component.products).toHaveResourceValue([product]);
2709
+ // after changing a signal the params() computation reads: flushEffects() before the next expectOne/expectRequest
2391
2710
 
2392
2711
  // ...or skip the request entirely when it is not what the spec is about
2393
- const products = mockResourceProp(service, 'products', []);
2394
- products.set([product]); // 'resolved' products.loading() products.fail('offline')
2395
- expect(products.reload).toHaveBeenCalled(); // reload is spied, and re-issues nothing
2712
+ const products = mockResourceProp(service, 'products', []); // { status: 'idle' } starts it unstarted
2713
+ products.set([product]); // 'resolved' products.loading() products.fail('offline') products.idle()
2714
+ service.products.set([edited]); // the component's own optimistic write — status → 'local'
2715
+ expect(products.reload).toHaveBeenCalled(); // reload is spied, answers true, and re-issues nothing
2396
2716
 
2397
2717
  // signal assertions
2398
2718
  registerSignalMatchers(); // once, in the setup file
@@ -2410,20 +2730,30 @@ Two zoneless traps:
2410
2730
  - `fixture.detectChanges()` runs **one** change-detection pass and does **not** flush pending
2411
2731
  effects. Asserting right after it reads state that has not finished computing. Use `await stable(fixture)`.
2412
2732
  - `expect(someSignal).toBeTruthy()` passes for **every** signal ever created — a signal is a
2413
- function. Use `toHaveSignalValue`, which also rejects the missing-parentheses mistake.
2733
+ function. Use `toHaveSignalValue`, which also rejects the missing-parentheses mistake — and a
2734
+ spy, which it refuses instead of calling.
2414
2735
 
2415
2736
  And one resource trap, which is the same shape one level up: an `httpResource()` reports `loading`
2416
2737
  with its **default** value until a tick _and_ a microtask after its response is flushed, so a spec
2417
2738
  that asserts too early asserts the default and passes. `settleResource` fails instead of passing
2418
2739
  emptily. Note the order — `flushEffects()` first (the request is issued there, not on creation),
2419
- then the flush, then the wait.
2740
+ then the flush, then the wait. The same trap wearing a different hat is a resource still `idle` when
2741
+ the wait ends: its `params()` computation returned `undefined`, the loader never ran, and `value()`
2742
+ is the default. `settleResource` refuses that too, naming the signal the computation reads;
2743
+ `{ allowIdle: true }` is the opt-out for a spec whose subject is the idle state. Each round is a tick
2744
+ plus a microtask, and from the third round an event-loop turn as well, so a loader on a real timer
2745
+ settles rather than burning the budget in microseconds.
2420
2746
 
2421
2747
  `toHaveResourceValue` is the matcher form of that trap and the reason to prefer it over
2422
2748
  `expect(products.value()).toEqual(...)`: it **fails an unresolved resource even when the default
2423
2749
  value matches**, and names the status it was in. And when the request is not what the spec is about
2424
2750
  at all, do not arrange one — `mockResourceProp(service, 'products', [])` replaces the property with
2425
- a double whose `set` / `fail` / `loading` move it directly, built from real `signal()`s so a
2426
- `computed()` downstream still recomputes. Nothing is in flight, so there is nothing to await.
2751
+ a double whose `set` / `fail` / `loading` / `idle` move it directly, built from real `signal()`s so a
2752
+ `computed()` downstream still recomputes. The double carries the whole of `ResourceRef`: `value` is
2753
+ writable and a write through it lands in `'local'`, `set` / `update` / `asReadonly` / `destroy` /
2754
+ `snapshot` behave as Angular's own do, and `hasValue()` is value-based rather than status-based —
2755
+ `true` while the resource is loading over a value that is defined, which is what Angular has answered
2756
+ since v20. Nothing is in flight, so there is nothing to await.
2427
2757
 
2428
2758
  Per-file timing, to find which specs actually pay for `TestBed`:
2429
2759
 
@@ -2547,7 +2877,7 @@ TestBed.overrideComponent(DashboardComponent, { remove: { imports: [ChartCompone
2547
2877
 
2548
2878
  const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
2549
2879
  expect(chart.series()).toEqual([1, 2, 3]); // a signal input stays a signal input
2550
- chart.pointSelected.emit(2); // outputs are EventEmitters; a model() stays a model
2880
+ chart.pointSelected.emit(2); // outputs are EventEmitters; a model() stays a model
2551
2881
  ```
2552
2882
 
2553
2883
  Copied from `ɵcmp` / `ɵdir` / `ɵpipe`: the selector, every input under its public name (transforms
@@ -2775,45 +3105,48 @@ export default [
2775
3105
  errors — `prefer-as-spy` (`TS2352`) and `no-mocked-for-spy` (`TS2322`). Spread its `rules` after a
2776
3106
  blanket downgrade so those keep their severity; do not copy the two names into a consumer's config.
2777
3107
 
2778
- | Rule | Level | Fix | Flags |
2779
- | --------------------------------- | ------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2780
- | `no-expect-in-subscribe` | `error` | suggest | `expect()` inside `subscribe()` → `expectEmission` / `firstValueFrom` |
2781
- | `no-object-define-property` | `error` | suggest | `Object.defineProperty` in a spec → `mockReadonlyProp` / `mockValueProp` |
2782
- | `prefer-provide-auto-spy` | `error` | — | a hand-rolled `useValue`, `useFactory`, `useClass` or `useExisting` (also `useValue: new StubMock()`), in a provider **or** a `TestBed.overrideProvider(X, { … })` → `provideAutoSpy(Class)` / `provideAutoSpyForToken(TOKEN)`. A name in the slot is followed one step, through an initialiser or a single `beforeEach` assignment |
2783
- | `prefer-create-spy-from-class` | `error` | — | an object literal of 2+ `vi.fn()`s → `createSpyFromClass` (a factory's own seed is exempt) |
2784
- | `no-stub-class-double` | `warn` | — | a class whose fields are `vi.fn()`s → `createSpyFromClass` / `provideAutoSpy` and delete the stub; a decorated, `implements`-ing, `extends`-ing or unnamed class is exempt — option: `{ minRunnerFns }` |
2785
- | `no-structural-double` | `warn` | — | an object of `vi.fn()`s bound to a name declared `{ load: Mock }` → `createAutoMock<T>()`; a bare `let fn: Mock` is a callback and never reported — option: `{ minRunnerFns }` |
2786
- | `prefer-inject-spy` | `error` | suggest | `vi.spyOn(TestBed.inject(X), 'm')`, inline or via a `const` → `injectSpy(X).m` |
2787
- | `no-shared-module-level-mock` | `error` | — | an **exported** value holding `vi.fn()`s → export a factory instead |
2788
- | `no-mocked-for-spy` | `error` | `--fix` / suggest | `Mocked<T>` in any type position → `Spy<T>`, import and all — a suggestion where the assigned value is not from a factory of this library |
2789
- | `prefer-as-spy` | `error` | `--fix` | `TestBed.inject(X) as Spy<X>` → `asSpy<X>(TestBed.inject(X))`, import and all |
2790
- | `no-done-callback` | `error` | — | `it('x', (done) => …)` → `async` + an awaited assertion, and `done.fail(…)` at the call site |
2791
- | `no-floating-assertion` | `error` | — | `expect()` in a `.then()` nobody awaits → `expect(await promise)` |
2792
- | `no-bare-called-with` | `error` | — | `spy.m.calledWith(1);` as a statement — a stub nobody continued, asserting nothing; chai's `expect(fn).to.have.been.calledWith()` exempt |
2793
- | `no-overridden-provider` | `error` | suggest | two providers for one token in one array, or one a `TestBed.overrideProvider` in the same hook replaces → the earlier one never runs; the exact duplicate can be deleted |
2794
- | `no-inject-before-override` | `error` | — | `TestBed.inject()` / `injectSpy()` / `renderShallow()` in a hook, in a suite that still calls `override*` |
2795
- | `no-private-member-access` | `error` | — | `instance['privateMember']`, `(instance as any).privateMember` (and `as unknown as`, and a decoy type), `vi.spyOn(Object.getPrototypeOf(x), 'm')` → drive the member through the public API. **Type-aware**: silent without `parserOptions.project`, and silent on an index signature |
2796
- | `no-dead-schemas` | `error` | — | `schemas` on a testing module with no `declarations` — the schema applies to nothing; the file decides, so a `declarations` in another `configureTestingModule` call silences it |
2797
- | `no-import-time-spread` | `error` | suggest | `export const x = [...Imported]` at module scope → a `TypeError` while the bundle loads |
2798
- | `no-unregistered-inject-spy` | `error` | — | `injectSpy(X)` for a token this file never registered → the real instance, whose spy helpers exist only for the compiler |
2799
- | `prefer-render-shallow` | `warn` | suggest | `TestBed.createComponent` in a file that never reads the template → `renderShallow(X)`; 0.24× the per-test cycle at 100 children |
2800
- | `prefer-observer-stub` | `error` | — | a hand-rolled observer global → `stubIntersectionObserver()` / `stubResizeObserver()` / `stubMutationObserver()`; the manual save-and-restore goes too, `restoreMockedProps()` runs the undo |
2801
- | `no-passthrough-console-spy` | `error` | suggest | `vi.spyOn(console, m)` nothing gives an implementation — it calls through and prints → `installConsoleSpies()` + `consoleXSpy`, or `.mockImplementation(() => undefined)` |
2802
- | `no-console-in-spec` | `error` | — | a spec calling `console.x(…)` itself, or `console.x = …`, which nothing restores → absorb the code's output through `vitest-auto-spy/console` |
2803
- | `no-import-time-console-spies` | `error` | — | an import of `vitest-auto-spy/console` in a file that never calls `installConsoleSpies()` — the import installs once per worker and silences every later file → `installConsoleSpies()` in `beforeEach`, `restoreConsole()` in `afterEach` |
2804
- | `no-mistyped-use-value` | `error` | — | `{ provide: TOKEN, useValue }` whose value is not assignable to the primitive `T` of `InjectionToken<T>` (string, number, boolean, bigint, enum, their literals, `null`, `undefined`) — `useValue` is `any`, so `{}` for a `boolean` token compiles and is truthy. **Type-aware**: silent without `parserOptions.project`; object-typed tokens are `no-unknown-use-value-key`'s |
2805
- | `no-unknown-use-value-key` | `error` | — | a key of an object `useValue` literal the provided type does not have — `T` of `InjectionToken<T>`, or the instance type of a `provide:` class; `{ provide: ActivatedRoute, useValue: { queryParams$: … } }` compiles, since `useValue` is `any`. Keys only, never assignability (a partial fixture is fine). **Type-aware**; silent on `any` / `unknown` / `object`, an index signature, a spread's keys, `multi: true` |
2806
- | `no-instance-lifecycle-spy` | `warn` | — | `vi.spyOn(instance, 'ngOnInit')` (and `ngOnDestroy`, `ngDoCheck`, `ngAfterContent*`, `ngAfterView*`) — a view calls the hook read off the prototype, so the instance spy is never called and its stub never runs → `vi.spyOn(Cls.prototype, …)` before `createComponent`, or assert the effect. `ngOnChanges` is exempt: Angular calls it through the instance |
2807
- | `no-ts-expect-error-on-double` | `error` | — | `@ts-expect-error` / `@ts-ignore` above `nextWith`, `resolveWith`, `mockReturnValue`, `returnValue`, `calledWith(…)` and the other helpers that check a stub against the method's signature → an overloaded method takes `Spy<X, { overload: { m: 'first' } }>`; otherwise the fixture is the wrong shape, checked against `ReturnType<X['m']>`. A reason after the directive does not silence it; a deliberate out-of-type value keeps it under `eslint-disable-next-line … -- <why>` |
2808
- | `no-constant-expect` | `error` | — | `expect(true).toBe(true)`, `expect({ … }).toBeDefined()` — a value the spec spelled out, under a matcher whose answer it already fixes (`toBe` / `toEqual` / `toStrictEqual` against a literal; `toBeTruthy`, `toBeDefined`, `toBeNull`… for any literal) → assert on what the code produced, or `expect.fail(…)` for an unreachable branch |
2809
- | `no-compile-components` | `error` | suggest | `compileComponents()` under a builder that inlines `templateUrl` / `styleUrls` — a promise already settled → delete it, and the `async` of a hook that awaits nothing else. **Silent until** `['error', { builder: 'inline-resources' }]`: under a JIT setup that loads resources at run time the call is load-bearing |
2810
- | `jasmine-namespace-without-entry` | `error` | — | `.and` / `.calls` / `.withArgs` on a library spy in a file that installs the compat layer nowhere — option: `{ setupModules: […] }` |
2811
- | `no-jasmine-globals` | `error` | — | `jasmine.*`, bare `spyOn(` / `spyOnProperty(` / `spyOnAllFunctions(` / `fail(` / `pending(`, `.withContext(` |
2812
- | `no-save-arguments-by-value` | `error` | — | `spy.calls.saveArgumentsByValue()` — a no-op here, so the spec silently asserts on post-mutation state |
2813
- | `prefer-native-spy-api` | `error` | `--fix` / suggest | `.and` / `.calls` where the spy's own API says the same thing — turn it on for the last mile off the jasmine shim |
2814
-
2815
- Thirty-four rules, **every one an `error` since 4.0.0 except `prefer-render-shallow`,
2816
- `no-stub-class-double`, `no-structural-double` and `no-instance-lifecycle-spy`**; three fix on their own, ten offer suggestions. Thirty-one are syntactic; `no-private-member-access`, `no-mistyped-use-value` and
3108
+ | Rule | Level | Fix | Flags |
3109
+ | --------------------------------- | ------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
3110
+ | `no-expect-in-subscribe` | `error` | suggest | `expect()` inside `subscribe()` → `expectEmission` / `firstValueFrom` |
3111
+ | `no-object-define-property` | `error` | suggest | `Object.defineProperty` in a spec → `mockReadonlyProp` / `mockValueProp` |
3112
+ | `prefer-provide-auto-spy` | `error` | — | a hand-rolled `useValue`, `useFactory`, `useClass` or `useExisting` (also `useValue: new StubMock()`), in a provider **or** a `TestBed.overrideProvider(X, { … })` → `provideAutoSpy(Class)` / `provideAutoSpyForToken(TOKEN)`. A name in the slot is followed one step, through an initialiser or a single `beforeEach` assignment |
3113
+ | `prefer-create-spy-from-class` | `error` | — | an object literal of 2+ `vi.fn()`s → `createSpyFromClass` (a factory's own seed is exempt) |
3114
+ | `no-stub-class-double` | `warn` | — | a class whose fields are `vi.fn()`s → `createSpyFromClass` / `provideAutoSpy` and delete the stub; a decorated, `implements`-ing, `extends`-ing or unnamed class is exempt — option: `{ minRunnerFns }` |
3115
+ | `no-structural-double` | `warn` | — | an object of `vi.fn()`s bound to a name declared `{ load: Mock }` → `createAutoMock<T>()`; a bare `let fn: Mock` is a callback and never reported — option: `{ minRunnerFns }` |
3116
+ | `prefer-inject-spy` | `error` | suggest | `vi.spyOn(TestBed.inject(X), 'm')`, inline or via a `const` → `injectSpy(X).m` |
3117
+ | `no-shared-module-level-mock` | `error` | — | an **exported** value holding `vi.fn()`s → export a factory instead |
3118
+ | `no-mocked-for-spy` | `error` | `--fix` / suggest | `Mocked<T>` in any type position → `Spy<T>`, import and all — a suggestion where the assigned value is not from a factory of this library |
3119
+ | `prefer-as-spy` | `error` | `--fix` | `TestBed.inject(X) as Spy<X>` → `asSpy<X>(TestBed.inject(X))`, import and all |
3120
+ | `no-done-callback` | `error` | — | `it('x', (done) => …)` → `async` + an awaited assertion, and `done.fail(…)` at the call site |
3121
+ | `no-floating-assertion` | `error` | — | `expect()` in a `.then()` nobody awaits → `expect(await promise)` |
3122
+ | `no-bare-called-with` | `error` | — | `spy.m.calledWith(1);` as a statement — a stub nobody continued, asserting nothing; chai's `expect(fn).to.have.been.calledWith()` exempt |
3123
+ | `no-overridden-provider` | `error` | suggest | two providers for one token in one array, or one a `TestBed.overrideProvider` in the same hook replaces → the earlier one never runs; the exact duplicate can be deleted |
3124
+ | `no-inject-before-override` | `error` | — | `TestBed.inject()` / `injectSpy()` / `renderShallow()` in a hook, in a suite that still calls `override*` |
3125
+ | `no-private-member-access` | `error` | — | `instance['privateMember']`, `(instance as any).privateMember` (and `as unknown as`, and a decoy type), `vi.spyOn(Object.getPrototypeOf(x), 'm')` → drive the member through the public API. **Type-aware**: silent without `parserOptions.project`, and silent on an index signature |
3126
+ | `no-dead-schemas` | `error` | — | `schemas` on a testing module with no `declarations` — the schema applies to nothing; the file decides, so a `declarations` in another `configureTestingModule` call silences it |
3127
+ | `no-import-time-spread` | `error` | suggest | `export const x = [...Imported]` at module scope → a `TypeError` while the bundle loads |
3128
+ | `no-unregistered-inject-spy` | `error` | — | `injectSpy(X)` for a token this file never registered → the real instance, whose spy helpers exist only for the compiler |
3129
+ | `prefer-render-shallow` | `warn` | suggest | `TestBed.createComponent` in a file that never reads the template → `renderShallow(X)`; 0.24× the per-test cycle at 100 children |
3130
+ | `prefer-observer-stub` | `error` | — | a hand-rolled observer global → `stubIntersectionObserver()` / `stubResizeObserver()` / `stubMutationObserver()`; the manual save-and-restore goes too, `restoreMockedProps()` runs the undo |
3131
+ | `prefer-provide-activated-route` | `error` | — | a hand-built `ActivatedRoute` — any `useValue` / `useClass` / `useFactory` / `useExisting`, and `provideAutoSpy(ActivatedRoute)` too → `provideActivatedRoute({ … })`; the double knows either the streams or the snapshot, never both, and `injectActivatedRoute().setParams(…)` moves them together mid-test |
3132
+ | `no-passthrough-console-spy` | `error` | suggest | `vi.spyOn(console, m)` nothing gives an implementation — it calls through and prints → `installConsoleSpies()` + `consoleXSpy`, or `.mockImplementation(() => undefined)` |
3133
+ | `no-console-in-spec` | `error` | — | a spec calling `console.x(…)` itself, or `console.x = …`, which nothing restores → absorb the code's output through `vitest-auto-spy/console` |
3134
+ | `no-import-time-console-spies` | `error` | — | an import of `vitest-auto-spy/console` in a file that never calls `installConsoleSpies()` — the import installs once per worker and silences every later file → `installConsoleSpies()` in `beforeEach`, `restoreConsole()` in `afterEach` |
3135
+ | `no-mistyped-use-value` | `error` | — | `{ provide: TOKEN, useValue }` whose value is not assignable to the primitive `T` of `InjectionToken<T>` (string, number, boolean, bigint, enum, their literals, `null`, `undefined`) — `useValue` is `any`, so `{}` for a `boolean` token compiles and is truthy. **Type-aware**: silent without `parserOptions.project`; object-typed tokens are `no-unknown-use-value-key`'s |
3136
+ | `no-unknown-use-value-key` | `error` | — | a key of an object `useValue` literal the provided type does not have — `T` of `InjectionToken<T>`, or the instance type of a `provide:` class; `{ provide: ActivatedRoute, useValue: { queryParams$: … } }` compiles, since `useValue` is `any`. Keys only, never assignability (a partial fixture is fine). **Type-aware**; silent on `any` / `unknown` / `object`, an index signature, a spread's keys, `multi: true` |
3137
+ | `no-instance-lifecycle-spy` | `warn` | — | `vi.spyOn(instance, 'ngOnInit')` (and `ngOnDestroy`, `ngDoCheck`, `ngAfterContent*`, `ngAfterView*`) — a view calls the hook read off the prototype, so the instance spy is never called and its stub never runs → `vi.spyOn(Cls.prototype, …)` before `createComponent`, or assert the effect. `ngOnChanges` is exempt: Angular calls it through the instance |
3138
+ | `no-ts-expect-error-on-double` | `error` | — | `@ts-expect-error` / `@ts-ignore` above `nextWith`, `resolveWith`, `mockReturnValue`, `returnValue`, `calledWith(…)` and the other helpers that check a stub against the method's signature → an overloaded method takes `Spy<X, { overload: { m: 'first' } }>`; otherwise the fixture is the wrong shape, checked against `ReturnType<X['m']>`. A reason after the directive does not silence it; a deliberate out-of-type value keeps it under `eslint-disable-next-line … -- <why>` |
3139
+ | `no-constant-expect` | `error` | — | `expect(true).toBe(true)`, `expect({ … }).toBeDefined()` — a value the spec spelled out, under a matcher whose answer it already fixes (`toBe` / `toEqual` / `toStrictEqual` against a literal; `toBeTruthy`, `toBeDefined`, `toBeNull`… for any literal) → assert on what the code produced, or `expect.fail(…)` for an unreachable branch |
3140
+ | `no-redundant-smoke-test` | `error` | suggest | `it('should create', () => expect(pipe).toBeTruthy())` — every statement of the body an `expect(x)` under `toBeTruthy` / `toBeDefined` / `toBeInstanceOf` (or their negated twins), weighed against the tests that run the same setup: the rest of the block, and everything the blocks nested in it declare → delete it; the suggestion removes the test and the blank line above it. Silent where that test is the block's only running one, and a skipped sibling does not count as proof |
3141
+ | `no-compile-components` | `error` | suggest | `compileComponents()` under a builder that inlines `templateUrl` / `styleUrls` — a promise already settled → delete it, and the `async` of a hook that awaits nothing else. **Silent until** `['error', { builder: 'inline-resources' }]`: under a JIT setup that loads resources at run time the call is load-bearing. **Keep the call for a component whose template holds a `@defer` block** — that ships async class metadata, which `TestBed` resolves in this very call whatever the builder did, and dropping it fails the test with `has unresolved metadata`; the rule cannot see another file's template, so such a call keeps its own `// eslint-disable-next-line vitest-auto-spy/no-compile-components -- @defer: async class metadata` |
3142
+ | `no-sync-testbed-await` | `error` | suggest | `await` on a TestBed call that answers the TestBed or a fixture — `configureTestingModule`, `override*`, `resetTestingModule`, `createComponent`, `getLastFixture`, through `TestBed`, `getTestBed()`, a chain of those, or a name holding one → drop the `await`, and the `async` of a hook that then awaits nothing else; the suggestion does both. Reads **no types**, so it reports without `parserOptions.project`, where `@typescript-eslint/await-thenable` cannot. `inject` and `runInInjectionContext` are never reported: each answers whatever the token or the callback holds, which can be a promise |
3143
+ | `jasmine-namespace-without-entry` | `error` | — | `.and` / `.calls` / `.withArgs` on a library spy in a file that installs the compat layer nowhere — option: `{ setupModules: […] }` |
3144
+ | `no-jasmine-globals` | `error` | — | `jasmine.*`, bare `spyOn(` / `spyOnProperty(` / `spyOnAllFunctions(` / `fail(` / `pending(`, `.withContext(` |
3145
+ | `no-save-arguments-by-value` | `error` | — | `spy.calls.saveArgumentsByValue()` — a no-op here, so the spec silently asserts on post-mutation state |
3146
+ | `prefer-native-spy-api` | `error` | `--fix` / suggest | `.and` / `.calls` where the spy's own API says the same thing — turn it on for the last mile off the jasmine shim |
3147
+
3148
+ Thirty-seven rules, **every one an `error` since 4.0.0 except `prefer-render-shallow`,
3149
+ `no-stub-class-double`, `no-structural-double` and `no-instance-lifecycle-spy`**; three fix on their own, twelve offer suggestions. Thirty-four are syntactic; `no-private-member-access`, `no-mistyped-use-value` and
2817
3150
  `no-unknown-use-value-key` read types, and all three report nothing at all without `parserOptions.project` / `projectService`
2818
3151
  rather than guessing. `no-compile-components` waits the same way for a fact no file holds — which
2819
3152
  builder the project has — and reports nothing until `{ builder: 'inline-resources' }` states it. The config used to be a graded mix of `error` / `warn` / `off`, which decided for the
@@ -2968,117 +3301,126 @@ packages, which a subpath export can never be.
2968
3301
 
2969
3302
  ## 17. Error → fix
2970
3303
 
2971
- | Message contains | Cause | Fix |
2972
- | ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2973
- | `No mock adapter registered` | no runtime entry was imported, or the wrong one | import `vitest-auto-spy` (Vitest) / `…/bun` / `…/node` once before creating spies |
2974
- | `Observable spies require rxjs` | the rxjs layer was never loaded | `import 'vitest-auto-spy/rxjs';` once, in the setup file |
2975
- | `Type 'SubjectLike<T>' is not assignable to type 'Subject<T>'` | 4.0.0: `returnSubject()` is rxjs-typed only where `vitest-auto-spy/rxjs` is in the TypeScript program, and it is not in this one | put `import 'vitest-auto-spy/rxjs';` in a file the spec `tsconfig` includes — a `setupFiles` entry outside `include` is the usual cause |
2976
- | `Cannot read properties of undefined (reading 'returnValue')` on `spy.m.and.…` | the jasmine namespaces are not installed — the spy was built before them, or nothing installed them at all | import from `vitest-auto-spy/jasmine`; on Bun / `node:test`, `enableJasmineCompat()` in the setup file (§20) |
2977
- | `spy.withArgs is not a function` | the same, seen from the argument-matching side | the same — or write `spy.m.calledWith(a).mockReturnValue(v)`, which needs no layer (§20) |
2978
- | `jasmine is not defined` | jasmine's global is the runner's, and Vitest declares none | `import { jasmine } from 'vitest-auto-spy/jasmine'`, then `codemod --from jasmine` to rewrite the members (§20) |
2979
- | `done.fail is not a function` | Vitest passes a `TestContext`, not jasmine's `done`; the line usually sits in an `error` callback nobody awaits, so the run stays **green** | assert on the failure — `await expect(firstValueFrom(src$)).rejects.toMatchObject({ … })`, or `expect.fail(message)` |
2980
- | a `.withContext('…')` message that never appears in the failure output | Vitest's chai layer has an `@internal` `withContext(flags)`; handed a string it walks the character indices, sets nonsense flags and returns `this` | `expect(actual, 'message').toBe(expected)` — the second argument of `expect` is the label. Nothing throws, so nothing warns (§20) |
2981
- | `names method(s) that are not on the class prototype` | typo, or an instance-field callable | fix the name, or move it to `instanceMethodsToSpyOn` |
2982
- | `All declarations of 'Matchers' must have identical type parameters` | a custom matcher declares `interface Matchers<T = any>` (the Vitest 4 shape) while Vitest 5 declares `Matchers<R, T>` | declare it on `Chai.Assertion` instead — that interface has no type parameters in either major, so one declaration merges on both (§10) |
2983
- | `toHaveBeenCalledTimes` reads `0` for a call an earlier test made, after moving to Vitest 5 | `clearMocks` defaults to `true` on Vitest 5, so `vi.clearAllMocks()` runs before every test | count the calls in a plain variable instead of reading the spy, or set `clearMocks: false` (§10) |
2984
- | `was configured with 'mustBeCalledWith'` | the code called the spy with other arguments | that is the assertion firing — fix the code, or relax to `calledWith` |
2985
- | `extendWithAutoSpies needs Vitest 4.1 or newer` | the `test` handed in has only the object-form `extend` (Vitest ≤ 4.0); the builder form the helper is written against arrived in 4.1 | upgrade Vitest, or keep `provideAutoSpy` + `injectSpy` in a `beforeEach` until then |
2986
- | `advanceTimers() requires fake timers` | no fake timers installed | `setupFakeTimers()` or `vi.useFakeTimers()` first |
2987
- | `Nothing configured X.method, and strict mode is on` | a strict double was asked for a method no line configured | configure it (`mockReturnValue` / `resolveWith` / `nextWith` / `calledWith`), or `{ strict: false }` on that double (§5) |
2988
- | `X.member was read N times and nothing configured it, and strict mode is on` (or `was subscribed to N times and nothing fed it`), after the test | `setupAutoSpy({ unconfiguredReads })` — the code under test read a strict double's spied getter and got `undefined`, or subscribed to its observable property and nothing ever emitted | configure it: `accessorSpies.getters.member.mockReturnValue(…)`, `overrides: { member }`, `mockReadonlyProp`; `nextWith` / `returnSubject` / `complete` for a stream; `mockReturnValue(undefined)` when `undefined` is the answer meant; `{ strict: false }` on that double (§5) |
2989
- | `[vitest-auto-spy] "…" wrote to the console N time(s) and nothing absorbed it` | `setupAutoSpy({ strayConsole })` — the test printed, and nothing that does not call through stood on `console`: no `/console` spy installed for it, no `mockImplementation`. A bare `vi.spyOn(console, m)` calls through, and a `console.warn` from this library counts too| absorb and assert: `installConsoleSpies()` in a `beforeEach`, then `expect(consoleErrorSpy)…`; or fix the code that printed. Importing a spy installs nothing under the guard. `strayConsole: { allow: [...] }` only for environment noise no spec can reach |
2990
- | `… wrote to the console N time(s) outside any test` | output while the file was imported, in a `beforeAll` / `afterAll`, from a callback after its test ended, or from a test whose `afterEach` never ran — the frame names the line | move the work into a test and absorb it there; a callback firing late is a leak — clear it where it is scheduled |
2991
- | `setupAutoSpy({ strict: true })` has no effect — no double throws, a suite with it on stays green | before this release the default lived in module scope, and `/setup` and the factory bundles each carried a copy; a 1759-file consumer ran 12 717 tests green with it on | upgrade — the default, `onUnstubbedCall` and `setSpyEngine()` now live on `globalThis` |
2992
- | a seeded getter reads `undefined`: `provideAutoSpy(X, { overrides: { remoteConfig } })` next to `gettersToSpyOn` or a `registerAutoSpyDefaults` row| before this release the seed was assigned into the spied accessor's setter, and the getter kept answering `undefined` | upgrade — `overrides` now seeds the getter spy; a later `accessorSpies.getters.x.mockReturnValue(…)` still wins |
2993
- | `Cannot read properties of undefined (reading 'name')` on `value.constructor.name`, with `createAutoMock<T>()`| `constructor` answered `undefined` on an auto-mock | upgrade — it answers `Object`, as every other double does; or seed it: `createAutoMock<T>({ constructor: … })` |
2994
- | `Cannot redefine property: …` from a library accessor spy | the target is an ES module namespace a bundler inlined | no spy library can win this — give the code a real seam (inject it, pass it in) and spy on that |
2995
- | `Cannot spy on this instance in place: it is not extensible` | `createSpyFromInstance` was handed a frozen or sealed object | spy it before it is frozen, or build a separate double with `createSpyFromClass` (§2) |
2996
- | `Cannot mock the property 'X': it is not configurable` | the member was defined with `configurable: false`, so it cannot be redefined | members replaced before it are still restorable — `restoreSpiedInstance(instance)` or `restoreMockedProps()` |
2997
- | `overrideComponentProvider(…): the override did not apply` | the component injects a different token, or a later `overrideProvider` won | pass the token the component actually injects (a base class, an `InjectionToken`), and override after nothing else re-configures |
2998
- | `the test ended with N unflushed HttpTestingController request(s)` | `enableAngularDiagnostics({ pendingRequests })` — nothing answered them | flush each (`controller.expectOne(url).flush(body)`), or `controller.verify()` where absence is the assertion (§13) |
2999
- | `NgModule(s) with an empty runtime scope: …` | `ngModuleScopes` (or `assertNgModuleScopes`) — an AOT test bundle stripped `ɵɵsetNgModuleScope`, so the import contributes nothing | declare what the spec needs in the TestBed module directly; pass only modules expected to bring declarations (§13) |
3000
- | `Cannot read properties of undefined`, stack inside the component's own constructor or a field initializer | a member the double must **hold** rather than spy on is read while the component is being constructed, and the `mockReadonlyProp` that seeds it is written _below_ `TestBed.createComponent` — so it has not run yet, and never will | seed it **before** construction: `provideAutoSpy(X, { overrides: { paymentParams: … } })`, or `provideAutoSpyForToken(TOKEN, { … })`. No later call can repair this — the throw happens inside `createComponent`, so the helper is not reached and cannot say so; the stack names the component (§9, §13) |
3001
- | `arr.map(asInstance)` infers `unknown[]` | `asInstance` is overloaded, and passing it **by reference** resolves against the `DeepMockProxy<T>` overload, from which `T` cannot be inferred | `arr.map((spy) => asInstance(spy))` — the arrow gives each call its own inference. For a fixed set, `asInstances(a, b, c)` keeps the tuple types (§6) |
3002
- | `Cannot read properties of undefined (reading 'provide')`, stack inside `render3/di_setup` | a barrel chunk had not run when the component's definition was built, so a provider slot is `undefined` | `assertComponentDefIntact(Cmp)` before `createComponent` — it names the list and the index (§13) |
3003
- | `assertComponentDefIntact(): argument N is undefined, which carries no ɵcmp or ɵdir` | the class reference itself never arrived — the `Cannot read properties of undefined (reading 'ɵcmp')` case | the same split barrel; import the component from its own module, not the barrel (§13) |
3004
- | `TS1117: An object literal cannot have multiple properties with the same name`, in a fixture | a hundred-line model literal copied into eight specs and edited independently | one `createFixtureFactory<T>(defaults)`; note the runtime keeps the **second** key, so do not auto-fix by dropping one (§12) |
3005
- | `configureTestingModule was given N schema(s) that can never apply` | `enableAngularDiagnostics({ deadSchemas })` — `schemas` next to a standalone component, with `declarations` empty | drop the `schemas` entry and put the missing directive/pipe in the component's own `imports`, or use `createDirectiveHost` (§13) |
3006
- | `injectSpy(X): the injector returned a plain instance, not an auto-spy` | the token is provided for real; a `console.warn` once per token and spec file, a **throw** under `enableAngularDiagnostics({ unspiedProviders })` or `setupAutoSpy({ misconfiguration: 'throw' })` | `provideAutoSpy(X)` / `provideAutoSpyForToken(TOKEN)`, or `TestBed.inject(X)` if the real thing is what the spec wants |
3007
- | `trackInjections(...).get(X): that token is not tracked by this log` | `get` only answers for tokens whose providers the log created | add the token to the `trackInjections([...])` list, or read it from the injector directly (§13) |
3008
- | `Spread syntax requires ...iterable[Symbol.iterator] to be a function`, at load time | a module-scope spread of an imported binding, inside a bundle | build the array in a function or a getter — `no-import-time-spread` (§16) |
3009
- | `the timers APIs are not mocked` in a nested `describe`'s `beforeAll` | fakes armed in `beforeEach` only; Jest armed them for the whole file | `setupFakeTimers(cfg, { betweenTests: true })` / `setupAutoSpy({ globalFakeTimers: true })` |
3010
- | setup-file hooks reaching only the first spec file of a worker | the setup module stayed cached (Angular unit-test builder + coverage) | run coverage with `--isolate`, or call `setupAutoSpy()` from a per-file module |
3011
- | `no DOM could be installed` | `bun-angular` preload with no DOM package | `bun add -d @happy-dom/global-registrator` (or `jsdom`) |
3012
- | `cannot read "…" referenced by …` | a `templateUrl` / `styleUrls` path does not resolve | fix the path, relative to the component file |
3013
- | duplicate-copy report from `setupAutoSpy()` | two installs, or one loaded as both ESM and CJS | dedupe the dependency; `setupAutoSpy({ duplicateCopies: 'warn' })` to downgrade |
3014
- | `Type 'Spy<T>' is not assignable to type 'T'` | `Spy<T>` drops private members — by design | declare as `Spy<T>`, or use `asInstance()` / `asSpy()` (§6) |
3015
- | a spy is never called, no warning | the method is an instance field, not on the prototype | `instanceMethodsToSpyOn`, or `createAutoMock<T>()` |
3016
- | `Cannot access '__vi_import_N__' before initialization` | `vi.mock()` on `@angular/core` or a relative path | you cannot mock it — the specs are bundled. Assert the result instead |
3017
- | `AggregateError at Object.dispatchError`, for a request nothing asserts on | jsdom really served an `XMLHttpRequest` — `blockNetwork` used to cover only `fetch` | `setupAutoSpy({ blockNetwork: true })`, or `{ xhr: 'empty' }` for tracker pings (§10) |
3018
- | `localStorage.setItem is not a function`, or `localStorage` undefined | Node's own Web Storage made Vitest's global filter skip the environment's — Node 25 and up, jsdom and happy-dom alike | on by default in `setupAutoSpy()`; `restoreWebStorage()` on its own (§10) |
3019
- | `Schedulers cannot synchronously execute watches while scheduling` | a timer from a **previous** file, under `isolate: false` | track and cancel pending timers/frames in the setup file (§10) |
3020
- | `signal read during notification phase` | same — a stray `requestAnimationFrame` callback | same |
3021
- | an assertion error printed to stderr, every test green and the run exiting 0 | zone.js swallowed a rejection nobody handled | `setupAutoSpy({ strayRejections: true })` fails the test it surfaced in (§10) |
3022
- | an `expect()` inside a `.then()` that never seems to run | nothing awaits the chain, so the test ended first | `await` the promise and assert the settled value — `no-floating-assertion` (§16) |
3023
- | `trackStrayRejections() found no zone.js on the host` | `strayRejections` turned on where zone.js is not loaded | `import 'zone.js';` in the setup file, or drop the option |
3024
- | `… .destroy is not a function` | an ngrx `rxMethod` replaced with a bare mock | `Object.assign(vi.fn(), { destroy: vi.fn() })` |
3025
- | `NullInjectorError` for a service you did provide | it is a component-level provider, not a module one | `asSpy(fixture.debugElement.injector.get(X))`, not `injectSpy(X)` |
3026
- | `runEffect(): … not an EffectRef returned by effect()` | passed the callback, a signal, or an unassigned field | pass what `effect()` returned; a field may need its lifecycle hook to run first |
3027
- | `X is not a constructor`, stack in production code | a `vi.fn(() => …)` where the code does `new X()` | `mockConstructor` / `stubConstructor` / `createSpyClass` (§12) |
3028
- | `Date is not a constructor` | `vi.spyOn(globalThis, 'Date')` — the fakes own it | `mockSystemTime(date)` / `vi.setSystemTime` |
3029
- | `TS2352: … 'accessorSpies' is missing in type 'X'` | `TestBed.inject(X) as Spy<X>` | `asSpy(TestBed.inject(X))` — never a double assertion (§6) |
3030
- | `TS2739` / `TS2740` / `TS2345` with `Spy<X>` on the left | a spy handed to an API typed against the class | `asInstance(spy)` (§6) |
3031
- | `is missing the following properties: _private, …` | declared as Vitest's `Mocked<T>` | declare `Spy<T>` (§6) |
3032
- | `AddPromiseSpyMethods<unknown>` vs `WithMockReturnValue<…>` | a generic class inferred as `Service<any>` | `asSpy<Service>(…)` / `injectSpy<Service>(…)` (§6) |
3033
- | `createComponentStub(): X carries no ɵcmp, ɵdir or ɵpipe to copy` | the class is not an Angular declaration, or the import resolved to `undefined` (a barrel split across chunks) | pass the `@Component` / `@Directive` / `@Pipe` class, imported from its own file (§13) |
3034
- | `'isKeyEnabled' does not exist in type 'MethodReturns<{ remoteConfig: any; }>'` | generic class: `createSpyFromClass(Config, { gettersToSpyOn: ['remoteConfig'], returns: { … } })` reads `T` back from the list, because the generic class argument is checked after the configuration | generic class: spell out the type argument — `createSpyFromClass<Config>(Config, …)`; `provideAutoSpy` from `/angular` infers it (§6) |
3035
- | `'addEventListener' called on an object that is not a valid instance of EventTarget` | Node's `AbortSignal` under jsdom + zone.js | `stubAbortController()` (§12) |
3036
- | `vi.requireMock is not a function` | a mechanical `jest.` → `vi.` rename | there is no equivalent — provide the double through the TestBed instead |
3037
- | a `vi.mock()` factory that never applies, only sometimes | under `isolate: false` the module was already in the worker's graph | do not mock it; inject the dependency, or `vi.hoisted()` + a real seam |
3038
- | a `vi.mock()` of a workspace alias that never applies at all | a bundler inlined the module before the mock could be installed | `assertMocked(ns, { specifier })` to prove it, then inject instead of mocking |
3039
- | `No "default" export is defined on the mock`, thrown inside a dependency | a factory returning bare named exports; the dep probes `default` | `vi.mock('x', () => moduleNamespace({ … }))` |
3040
- | `Not implemented: HTMLMediaElement.play`, or `duration` is `NaN` and cannot be set | jsdom implements the media elements as a shell | `stubMediaElement({ duration })`, then `media.set(el, …)` to fire the events |
3041
- | `Cannot set base providers because it has already been called` | zone and zoneless spec files sharing one worker | `setupAngularTestEnv({ zoneless, initZone, initZoneless })` (§13) |
3042
- | a stub that works in the first test of the file and in no other | installed at `describe` level or in `beforeAll`, then restored away | install it in `beforeEach`, or `installPerTest(() => stub…())` |
3043
- | a third-party library failing every other run, no test named | a test sealed a global with `Object.defineProperty` (non-configurable) | `setupAutoSpy({ guardGlobals: 'throw' })` names the file; then `mockValueProp` |
3044
- | a block of files reported as failed suites with no stack, and zero failing tests | a test left an own enumerable key on `Object.prototype`; `mergeHooks` spreads it and collection dies | `setupAutoSpy()` guards it by default; `prototypePollution` tunes the reaction |
3045
- | `expected [ { at: 1, …(5) }, …(8) ] to deeply equal [ { …(6) }, … ]` | one field moved in every element — usually a frozen clock or an id | `expect(diffByField(actual, expected)).toBeUndefined()` |
3046
- | a hand-tuned number of turns waiting for a `resource()` to load | a resource needs a change-detection **tick**, not event-loop turns; `flushEventLoopUntil` never ticks and the resource never even issues its request | `flushEffects()`, flush the request, then `await settleResource(r, { label })` |
3047
- | a `resource()` assertion that passes but reads the **default** value | the spec asserted before the resource left `loading` | `await settleResource(r, { label })` — it fails loudly instead |
3048
- | a spec dying on the runner's 5 s file timeout right after `await stable(fixture)` | the fixture never stabilised — an unflushed request, a real `setInterval` | `stable` now fails at 2000 ms naming the cause; raise `{ timeout }` only once neither is true |
3049
- | `flushEventLoopUntil` timing out on the **first** such test only, the rest green | a cold dynamic `import()` outran the turn budget; later tests hit the module cache | `await settleDynamicImport(() => import('…'))` — await the module, do not count turns |
3050
- | `Expected to be running in 'ProxyZone', but it was not found` | `zone.js/testing` patches jasmine/mocha/jest, not Vitest | `import 'vitest-auto-spy/zone'` after zone.js, with `globals: true` (§14) |
3051
- | `nextWith` demanding `HttpEvent<T>` on a generated API client | `Parameters`/`ReturnType` read the **last** overload | `asSpy<Client, { overload: 'first' }>(…)`, or `Overload<M, 0>` — never `@ts-expect-error`, which `no-ts-expect-error-on-double` reports (§16) |
3052
- | `NG0303` / `NG0304` / nothing at all, from a directive spec | the host is `standalone: false`, or the module is in the TestBed | `createDirectiveHost({ template, scope: [Module] })` (§13) |
3053
- | `TS2540: Cannot assign to 'X' because it is a read-only property` | a `readonly` field of an object under test | `mockValueProp(obj, 'X', value)` — on a class **getter**, `mockReadonlyProp` |
3054
- | `TypeError: Cannot read properties of undefined (reading 'mockReturnValue')` | the member is an **instance field**, not on the prototype — `Router.currentNavigation` since Angular 20 | `provideAutoSpy(Router, { instanceMethodsToSpyOn: ['currentNavigation'] })` (§5) |
3055
- | `throwWith` reaching the success branch first, with the previous test's value | the spy's `ReplaySubject(1)` outlived the test that filled it | upgrade; and `resetAutoSpy(spy)` in `beforeEach` when the TestBed is built in `beforeAll` |
3056
- | `TS2540` on a `Spy<T>` / `createAutoMock` member, which the runtime writes fine | `Spy<T>` is homomorphic and keeps the `readonly` of the source member — deliberately: on a member replaced by a **spied accessor** the assignment reaches the setter spy and the getter still answers `undefined`, so the type error is the loud version of a silent no-op | `mockValueProp(spy, 'X', value)` — it defines rather than assigns, so it works in both cases; `Mutable<Spy<T>>` is the opt-in for plain data members, and `Reflect.set` is **not** a way round it |
3057
- | `TS2345` from `mockReturnValue` / `mockImplementation` / `mockResolvedValue` on a double that used to compile | the mock surface is `MockInstance<Method>`, so the stub is now checked against the method's own return type | stub with what the method returns; if the double is meant to answer something else, the method's type or the spec's expectation is wrong |
3058
- | `delete mock.optionalMethod` leaving the member present and truthy | the Proxy had no `deleteProperty` trap before 3.5.0 | upgrade; before that, `mock.optionalMethod = undefined` |
3059
- | half a double's methods reaching the real implementation after `Object.assign` | `ownKeys` on a type-driven Proxy lists only the keys already read | `createSpyFromClass(X)` — a real object, with enumerable method keys |
3060
- | `let s: MockInstance<() => unknown>` not matching anything | `MockInstance<F>` is invariant in `F`; Jest's `SpyInstance` was not | `MockInstance<T['method']>`, or better `injectSpy(X).method` |
3061
- | two runs with the same totals, one of them missing a suite | a lost `describe` and a fixed flake cancel out in the counters | `compareTestRuns(before, after)` — compare the set of names, not the numbers |
3062
- | a 30 s timeout, in a different file each run | module-level `vi.fn()` in a fixture shared by files | make the fixture a factory (§10) |
3063
- | a component's `afterNextRender` state is empty | `detectChanges()` does not run the after-render phase | `await stable(fixture)` (§11) |
3064
- | a green test whose only line about a call is `spy.m.calledWith(1);` | that is a **stub**, not an assertion — chai's `expect(fn).to.have.been.calledWith(x)` is the one that checks | continue the chain, or `expect(spy.m).toHaveBeenCalledWith(1)` — `no-bare-called-with` (§16) |
3065
- | `--detect-async-leaks` reporting no leaks in a suite that visibly leaks timers | `setupAutoSpy({ strayTimers: true })` cancelled them before Vitest collected | the warning on stderr says how many were taken and where the first three were scheduled; `onStrayTimers` gets every one in `timers` (§10) |
3066
- | `createNestUnit(X): parameter #n of Y is typed as \`Object\``(or`undefined — usually a circular import`) | the compiler emitted no runtime class for that parameter — interface, union, primitive, or a circular import | `@Inject(TOKEN)` plus a `providers` entry, or `@Optional()` to receive `undefined`; `@Inject(forwardRef(() => X))` for the import cycle |
3067
- | `createNestUnit(X): Y declares n constructor parameter(s) but carries no design:paramtypes metadata` | no `emitDecoratorMetadata` (esbuild / Vite), or `reflect-metadata` loaded after the class | tsc or SWC with `decoratorMetadata`, `@Injectable()`, `reflect-metadata` first; or `@Inject(X)` on every parameter |
3068
- | `createNestUnit(X): A -> B -> A is a cycle among the classes built for real` | two exposed / `useClass` classes depend on each other; the helper does not resolve `forwardRef` cycles | expose one side less, or provide it |
3069
- | `createNestUnit(X).spies.get(Y): the unit never asked for that token` | same guard as `createWithAutoSpies` — the spy would not be the one the unit uses | stub the token the unit actually injects (the message lists the auto-spied ones) |
3070
- | `createNestUnit(X).spies.get(Y): Y is in \`expose\`, so the unit got a real instance` | an exposed class is real, not a spy | read the spies of its own collaborators, or drop it from `expose` |
3071
- | `expect(component.ngOnInit).toHaveBeenCalled()` fails after `fixture.detectChanges()`, or a hook's `.mockImplementation` never runs | the spy was put on the **instance**; a view calls the hook it read off the class prototype when the component was created | `vi.spyOn(Cls.prototype, 'ngOnInit')` before `TestBed.createComponent`, or assert what the hook does — `no-instance-lifecycle-spy` (§16) |
3072
- | `TS2345: Argument of type 'InjectionToken<X>' is not assignable to parameter of type 'ClassType<unknown>'`, on `registerAutoSpyDefaults` | the core entry's `registerAutoSpyDefaults` takes a class only — it may not name Angular's token type | import `registerAutoSpyDefaults` (and `clearAutoSpyDefaults`) from `vitest-auto-spy/angular`, which also takes an `InjectionToken` (§5) |
3073
- | `selfReturning names 'x', which is not a spied method` | the name is not a method of the double — a typo, or a restricting `onlyMethodsToSpyOn` left it out; on a type-driven double, `then` and `constructor` are never spies | fix the name or the whitelist; the value is silently never returned otherwise (§5) |
3074
- | a spec green over a `useValue` fixture whose key the code never reads — `queryParams$` on an `ActivatedRoute` | `useValue` is `any`, so a renamed or misspelled key of an object literal compiles | the member's real name — `no-unknown-use-value-key` (§16), with type information; or `provideAutoSpy(X, { overrides })`, which the compiler checks |
3075
- | a spec runs down the "browser" (or any flag-on) branch whatever its `useValue` says | `{ provide: IS_BROWSER, useValue: {} }` for an `InjectionToken<boolean>` — `useValue` is `any`, and an object is truthy | a value of the token's type (`useValue: false`) — `no-mistyped-use-value` (§16), with type information |
3076
- | `no request matched …` (with the requests that were made listed) | the URL, verb or predicate does not describe anything the code under test sent, or nothing subscribed | read the list in the message — it is the requests that were actually made; then fix the URL, add `{ method }`, or subscribe (§13) |
3077
- | `this TestBed has no HttpTestingController` | `expectRequest` / `expectNoRequest` on a module that never got the testing backend | `TestBed.configureTestingModule({ providers: [...provideHttpTesting()] })` from `vitest-auto-spy/angular-http` (§13) |
3078
- | `the test ended with N unanswered request(s)` | `provideHttpTesting({ verifyOnTeardown })` found a request the spec never flushed | answer it (`await expectRequest(url).flush(body)`), assert its absence (`expectNoRequest(url)`), or `{ verifyOnTeardown: false }` (§13) |
3079
- | `injectActivatedRoute(): nothing provides ActivatedRoute here` | no `ActivatedRoute` provider in the injector it read | `provideActivatedRoute({ … })` from `vitest-auto-spy/angular-router` in `providers`; `injectActivatedRoute(fixture.debugElement.injector)` for a component-level one (§13) |
3080
- | `the ActivatedRoute here is … not one provideActivatedRoute() built` | a later provider of `ActivatedRoute` won — `provideRouter()`, `RouterModule`, a `useValue`, `provideAutoSpy(ActivatedRoute)` | list `provideActivatedRoute()` last, or drop the other provider (§13) |
3081
- | `provideActivatedRoute: the installed @angular/router does not wire ActivatedRoute …` | a router major builds `ActivatedRoute` with different internal constructors | report it with the `@angular/router` version; provide the route by hand until then (§13) |
3304
+ | Message contains | Cause | Fix |
3305
+ | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
3306
+ | `No mock adapter registered` | no runtime entry was imported, or the wrong one | import `vitest-auto-spy` (Vitest) / `…/bun` / `…/node` once before creating spies |
3307
+ | `Observable spies require rxjs` | the rxjs layer was never loaded | `import 'vitest-auto-spy/rxjs';` once, in the setup file |
3308
+ | `Type 'SubjectLike<T>' is not assignable to type 'Subject<T>'` | 4.0.0: `returnSubject()` is rxjs-typed only where `vitest-auto-spy/rxjs` is in the TypeScript program, and it is not in this one | put `import 'vitest-auto-spy/rxjs';` in a file the spec `tsconfig` includes — a `setupFiles` entry outside `include` is the usual cause |
3309
+ | `Cannot read properties of undefined (reading 'returnValue')` on `spy.m.and.…` | the jasmine namespaces are not installed — the spy was built before them, or nothing installed them at all | import from `vitest-auto-spy/jasmine`; on Bun / `node:test`, `enableJasmineCompat()` in the setup file (§20) |
3310
+ | `spy.withArgs is not a function` | the same, seen from the argument-matching side | the same — or write `spy.m.calledWith(a).mockReturnValue(v)`, which needs no layer (§20) |
3311
+ | `jasmine is not defined` | jasmine's global is the runner's, and Vitest declares none | `import { jasmine } from 'vitest-auto-spy/jasmine'`, then `codemod --from jasmine` to rewrite the members (§20) |
3312
+ | `done.fail is not a function` | Vitest passes a `TestContext`, not jasmine's `done`; the line usually sits in an `error` callback nobody awaits, so the run stays **green** | assert on the failure — `await expect(firstValueFrom(src$)).rejects.toMatchObject({ … })`, or `expect.fail(message)` |
3313
+ | a `.withContext('…')` message that never appears in the failure output | Vitest's chai layer has an `@internal` `withContext(flags)`; handed a string it walks the character indices, sets nonsense flags and returns `this` | `expect(actual, 'message').toBe(expected)` — the second argument of `expect` is the label. Nothing throws, so nothing warns (§20) |
3314
+ | `names method(s) that are not on the class prototype` | typo, or an instance-field callable | fix the name, or move it to `instanceMethodsToSpyOn` |
3315
+ | `All declarations of 'Matchers' must have identical type parameters` | a custom matcher declares `interface Matchers<T = any>` (the Vitest 4 shape) while Vitest 5 declares `Matchers<R, T>` | declare it on `Chai.Assertion` instead — that interface has no type parameters in either major, so one declaration merges on both (§10) |
3316
+ | `toHaveBeenCalledTimes` reads `0` for a call an earlier test made, after moving to Vitest 5 | `clearMocks` defaults to `true` on Vitest 5, so `vi.clearAllMocks()` runs before every test | count the calls in a plain variable instead of reading the spy, or set `clearMocks: false` (§10) |
3317
+ | `was configured with 'mustBeCalledWith'` | the code called the spy with other arguments | that is the assertion firing — fix the code, or relax to `calledWith` |
3318
+ | `extendWithAutoSpies needs Vitest 4.1 or newer` | the `test` handed in has only the object-form `extend` (Vitest ≤ 4.0); the builder form the helper is written against arrived in 4.1 | upgrade Vitest, or keep `provideAutoSpy` + `injectSpy` in a `beforeEach` until then |
3319
+ | `advanceTimers() requires fake timers` | no fake timers installed | `setupFakeTimers()` or `vi.useFakeTimers()` first |
3320
+ | `Nothing configured X.method, and strict mode is on` | a strict double was asked for a method no line configured | configure it (`mockReturnValue` / `resolveWith` / `nextWith` / `calledWith`), or `{ strict: false }` on that double (§5) |
3321
+ | `X.member was read N times and nothing configured it, and strict mode is on` (or `was subscribed to N times and nothing fed it`), after the test | `setupAutoSpy({ unconfiguredReads })` — the code under test read a strict double's spied getter and got `undefined`, or subscribed to its observable property and nothing ever emitted | configure it: `accessorSpies.getters.member.mockReturnValue(…)`, `overrides: { member }`, `mockReadonlyProp`; `nextWith` / `returnSubject` / `complete` for a stream; `mockReturnValue(undefined)` when `undefined` is the answer meant; `{ strict: false }` on that double (§5) |
3322
+ | `[vitest-auto-spy] "…" wrote to the console N time(s) and nothing absorbed it` | `setupAutoSpy({ strayConsole })` — the test printed, and nothing that does not call through stood on `console`: no `/console` spy installed for it, no `mockImplementation`. A bare `vi.spyOn(console, m)` calls through, and a `console.warn` from this library counts too | absorb and assert: `installConsoleSpies()` in a `beforeEach`, then `expect(consoleErrorSpy)…`; or fix the code that printed. Importing a spy installs nothing under the guard. `strayConsole: { allow: [...] }` only for environment noise no spec can reach |
3323
+ | `… wrote to the console N time(s) outside any test` | output while the file was imported, in a `beforeAll` / `afterAll`, from a callback after its test ended, or from a test whose `afterEach` never ran — the frame names the line | move the work into a test and absorb it there; a callback firing late is a leak — clear it where it is scheduled |
3324
+ | `setupAutoSpy({ strict: true })` has no effect — no double throws, a suite with it on stays green | before this release the default lived in module scope, and `/setup` and the factory bundles each carried a copy; a 1759-file consumer ran 12 717 tests green with it on | upgrade — the default, `onUnstubbedCall` and `setSpyEngine()` now live on `globalThis` |
3325
+ | a seeded getter reads `undefined`: `provideAutoSpy(X, { overrides: { remoteConfig } })` next to `gettersToSpyOn` or a `registerAutoSpyDefaults` row | before this release the seed was assigned into the spied accessor's setter, and the getter kept answering `undefined` | upgrade — `overrides` now seeds the getter spy; a later `accessorSpies.getters.x.mockReturnValue(…)` still wins |
3326
+ | `Cannot read properties of undefined (reading 'name')` on `value.constructor.name`, with `createAutoMock<T>()` | `constructor` answered `undefined` on an auto-mock | upgrade — it answers `Object`, as every other double does; or seed it: `createAutoMock<T>({ constructor: … })` |
3327
+ | `Cannot redefine property: …` from a library accessor spy | the target is an ES module namespace a bundler inlined | no spy library can win this — give the code a real seam (inject it, pass it in) and spy on that |
3328
+ | `Cannot spy on this instance in place: it is not extensible` | `createSpyFromInstance` was handed a frozen or sealed object | spy it before it is frozen, or build a separate double with `createSpyFromClass` (§2) |
3329
+ | `Cannot mock the property 'X': it is not configurable` | the member was defined with `configurable: false`, so it cannot be redefined | members replaced before it are still restorable — `restoreSpiedInstance(instance)` or `restoreMockedProps()` |
3330
+ | `overrideComponentProvider(…): the override did not apply` | the component injects a different token, or a later `overrideProvider` won | pass the token the component actually injects (a base class, an `InjectionToken`), and override after nothing else re-configures |
3331
+ | `the test ended with N unflushed HttpTestingController request(s)` | `enableAngularDiagnostics({ pendingRequests })` — nothing answered them | flush each (`controller.expectOne(url).flush(body)`), or `controller.verify()` where absence is the assertion (§13) |
3332
+ | `NgModule(s) with an empty runtime scope: …` | `ngModuleScopes` (or `assertNgModuleScopes`) — an AOT test bundle stripped `ɵɵsetNgModuleScope`, so the import contributes nothing | declare what the spec needs in the TestBed module directly; pass only modules expected to bring declarations (§13) |
3333
+ | `Cannot read properties of undefined`, stack inside the component's own constructor or a field initializer | a member the double must **hold** rather than spy on is read while the component is being constructed, and the `mockReadonlyProp` that seeds it is written _below_ `TestBed.createComponent` — so it has not run yet, and never will | seed it **before** construction: `provideAutoSpy(X, { overrides: { paymentParams: … } })`, or `provideAutoSpyForToken(TOKEN, { … })`. No later call can repair this — the throw happens inside `createComponent`, so the helper is not reached and cannot say so; the stack names the component (§9, §13) |
3334
+ | `arr.map(asInstance)` infers `unknown[]` | `asInstance` is overloaded, and passing it **by reference** resolves against the `DeepMockProxy<T>` overload, from which `T` cannot be inferred | `arr.map((spy) => asInstance(spy))` — the arrow gives each call its own inference. For a fixed set, `asInstances(a, b, c)` keeps the tuple types (§6) |
3335
+ | `Cannot read properties of undefined (reading 'provide')`, stack inside `render3/di_setup` | a barrel chunk had not run when the component's definition was built, so a provider slot is `undefined` | `assertComponentDefIntact(Cmp)` before `createComponent` — it names the list and the index (§13) |
3336
+ | `assertComponentDefIntact(): argument N is undefined, which carries no ɵcmp or ɵdir` | the class reference itself never arrived — the `Cannot read properties of undefined (reading 'ɵcmp')` case | the same split barrel; import the component from its own module, not the barrel (§13) |
3337
+ | `TS1117: An object literal cannot have multiple properties with the same name`, in a fixture | a hundred-line model literal copied into eight specs and edited independently | one `createFixtureFactory<T>(defaults)`; note the runtime keeps the **second** key, so do not auto-fix by dropping one (§12) |
3338
+ | `configureTestingModule was given N schema(s) that can never apply` | `enableAngularDiagnostics({ deadSchemas })` — `schemas` next to a standalone component, with `declarations` empty | drop the `schemas` entry and put the missing directive/pipe in the component's own `imports`, or use `createDirectiveHost` (§13) |
3339
+ | `injectSpy(X): the injector returned a plain instance, not an auto-spy` | the token is provided for real; a `console.warn` once per token and spec file, a **throw** under `enableAngularDiagnostics({ unspiedProviders })` or `setupAutoSpy({ misconfiguration: 'throw' })` | `provideAutoSpy(X)` / `provideAutoSpyForToken(TOKEN)`, or `TestBed.inject(X)` if the real thing is what the spec wants |
3340
+ | `trackInjections(...).get(X): that token is not tracked by this log` | `get` only answers for tokens whose providers the log created | add the token to the `trackInjections([...])` list, or read it from the injector directly (§13) |
3341
+ | `Spread syntax requires ...iterable[Symbol.iterator] to be a function`, at load time | a module-scope spread of an imported binding, inside a bundle | build the array in a function or a getter — `no-import-time-spread` (§16) |
3342
+ | `the timers APIs are not mocked` in a nested `describe`'s `beforeAll` | fakes armed in `beforeEach` only; Jest armed them for the whole file | `setupFakeTimers(cfg, { betweenTests: true })` / `setupAutoSpy({ globalFakeTimers: true })` |
3343
+ | setup-file hooks reaching only the first spec file of a worker | the setup module stayed cached (Angular unit-test builder + coverage) | run coverage with `--isolate`, or call `setupAutoSpy()` from a per-file module |
3344
+ | `no DOM could be installed` | `bun-angular` preload with no DOM package | `bun add -d @happy-dom/global-registrator` (or `jsdom`) |
3345
+ | `cannot read "…" referenced by …` | a `templateUrl` / `styleUrls` path does not resolve | fix the path, relative to the component file |
3346
+ | duplicate-copy report from `setupAutoSpy()` | two installs, or one loaded as both ESM and CJS | dedupe the dependency; `setupAutoSpy({ duplicateCopies: 'warn' })` to downgrade. A setup file that initialises the Angular test environment before the library loads splits Angular the same way — two copies, a second `TestBed`, and `No mock adapter registered` or overrides that never apply: `resolve.dedupe: ['@angular/core', '@angular/common', '@angular/platform-browser', '@angular/compiler', 'rxjs']` plus `test.server.deps.inline: ['vitest-auto-spy']` (Vitest 1 and up) leaves one copy of each |
3347
+ | `Type 'Spy<T>' is not assignable to type 'T'` | `Spy<T>` drops private members — by design | declare as `Spy<T>`, or use `asInstance()` / `asSpy()` (§6) |
3348
+ | a spy is never called, no warning | the method is an instance field, not on the prototype | `instanceMethodsToSpyOn`, or `createAutoMock<T>()` |
3349
+ | `Cannot access '__vi_import_N__' before initialization` | `vi.mock()` on `@angular/core` or a relative path | you cannot mock it — the specs are bundled. Assert the result instead |
3350
+ | `AggregateError at Object.dispatchError`, for a request nothing asserts on | jsdom really served an `XMLHttpRequest` — `blockNetwork` used to cover only `fetch` | `setupAutoSpy({ blockNetwork: true })`, or `{ xhr: 'empty' }` for tracker pings (§10) |
3351
+ | `localStorage.setItem is not a function`, or `localStorage` undefined | Node's own Web Storage made Vitest's global filter skip the environment's — Node 25 and up, jsdom and happy-dom alike | on by default in `setupAutoSpy()`; `restoreWebStorage()` on its own (§10) |
3352
+ | `Schedulers cannot synchronously execute watches while scheduling` | a timer from a **previous** file, under `isolate: false` | track and cancel pending timers/frames in the setup file (§10) |
3353
+ | `signal read during notification phase` | same — a stray `requestAnimationFrame` callback | same |
3354
+ | an assertion error printed to stderr, every test green and the run exiting 0 | zone.js swallowed a rejection nobody handled | `setupAutoSpy({ strayRejections: true })` fails the test it surfaced in (§10) |
3355
+ | an `expect()` inside a `.then()` that never seems to run | nothing awaits the chain, so the test ended first | `await` the promise and assert the settled value — `no-floating-assertion` (§16) |
3356
+ | `trackStrayRejections() found no zone.js on the host` | `strayRejections` turned on where zone.js is not loaded | `import 'zone.js';` in the setup file, or drop the option |
3357
+ | `… .destroy is not a function` | an ngrx `rxMethod` replaced with a bare mock | `Object.assign(vi.fn(), { destroy: vi.fn() })` |
3358
+ | `NullInjectorError` for a service you did provide | it is a component-level provider, not a module one | `asSpy(fixture.debugElement.injector.get(X))`, not `injectSpy(X)` |
3359
+ | `runEffect(): … not an EffectRef returned by effect()` | passed the callback, a signal, or an unassigned field | pass what `effect()` returned; a field may need its lifecycle hook to run first |
3360
+ | `runEffect(): this effect has been destroyed` | the fixture was destroyed, or effectRef.destroy() ran | move the call above `fixture.destroy()`, or assert what the teardown left behind |
3361
+ | `trackRecomputations(): this signal keeps no computation` | a plain `signal()`, which holds a value rather than computing one | track the `computed()` that reads it, or `trackEffectRuns()` the effect that does |
3362
+ | `mockSignalProp: '…' is an input() signal` | an `input()` replaced instead of set | `fixture.componentRef.setInput(name, value)`, or `renderShallow(C, { inputs: { … } })` |
3363
+ | `mockSignalProp: '…' is a read-only signal something has already read` | a `computed()` member swapped after the first render | patch before the first `detectChanges()` / `stable(fixture)`, or expose the member as a writable `signal()` |
3364
+ | `expected a signal (a zero-argument getter), received a spy` | `toHaveSignalValue` was handed a spied method instead of a signal — usually a typo, or a signal member spied as a method | assert the spy itself with `toHaveBeenCalled`, or put a real signal on the property with `mockSignalProp`; the matcher refuses it rather than calling it |
3365
+ | `X is not a constructor`, stack in production code | a `vi.fn(() => …)` where the code does `new X()` | `mockConstructor` / `stubConstructor` / `createSpyClass` (§12) |
3366
+ | `Date is not a constructor` | `vi.spyOn(globalThis, 'Date')` — the fakes own it | `mockSystemTime(date)` / `vi.setSystemTime` |
3367
+ | `TS2352: … 'accessorSpies' is missing in type 'X'` | `TestBed.inject(X) as Spy<X>` | `asSpy(TestBed.inject(X))` — never a double assertion (§6) |
3368
+ | `TS2739` / `TS2740` / `TS2345` with `Spy<X>` on the left | a spy handed to an API typed against the class | `asInstance(spy)` (§6) |
3369
+ | `is missing the following properties: _private, …` | declared as Vitest's `Mocked<T>` | declare `Spy<T>` (§6) |
3370
+ | `AddPromiseSpyMethods<unknown>` vs `WithMockReturnValue<…>` | a generic class inferred as `Service<any>` | `asSpy<Service>(…)` / `injectSpy<Service>(…)` (§6) |
3371
+ | `createComponentStub(): X carries no ɵcmp, ɵdir or ɵpipe to copy` | the class is not an Angular declaration, or the import resolved to `undefined` (a barrel split across chunks) | pass the `@Component` / `@Directive` / `@Pipe` class, imported from its own file (§13) |
3372
+ | `'isKeyEnabled' does not exist in type 'MethodReturns<{ remoteConfig: any; }>'` | generic class: `createSpyFromClass(Config, { gettersToSpyOn: ['remoteConfig'], returns: { … } })` reads `T` back from the list, because the generic class argument is checked after the configuration | generic class: spell out the type argument — `createSpyFromClass<Config>(Config, …)`; `provideAutoSpy` from `/angular` infers it (§6) |
3373
+ | `'addEventListener' called on an object that is not a valid instance of EventTarget` | Node's `AbortSignal` under jsdom + zone.js | `stubAbortController()` (§12) |
3374
+ | `vi.requireMock is not a function` | a mechanical `jest.` → `vi.` rename | there is no equivalent — provide the double through the TestBed instead |
3375
+ | a `vi.mock()` factory that never applies, only sometimes | under `isolate: false` the module was already in the worker's graph | do not mock it; inject the dependency, or `vi.hoisted()` + a real seam |
3376
+ | a `vi.mock()` of a workspace alias that never applies at all | a bundler inlined the module before the mock could be installed | `assertMocked(ns, { specifier })` to prove it, then inject instead of mocking |
3377
+ | `No "default" export is defined on the mock`, thrown inside a dependency | a factory returning bare named exports; the dep probes `default` | `vi.mock('x', () => moduleNamespace({ … }))` |
3378
+ | `Not implemented: HTMLMediaElement.play`, or `duration` is `NaN` and cannot be set | jsdom implements the media elements as a shell | `stubMediaElement({ duration })`, then `media.set(el, …)` to fire the events |
3379
+ | `Cannot set base providers because it has already been called` | zone and zoneless spec files sharing one worker | `setupAngularTestEnv({ zoneless, initZone, initZoneless })` (§13) |
3380
+ | a stub that works in the first test of the file and in no other | installed at `describe` level or in `beforeAll`, then restored away | install it in `beforeEach`, or `installPerTest(() => stub…())` |
3381
+ | a third-party library failing every other run, no test named | a test sealed a global with `Object.defineProperty` (non-configurable) | `setupAutoSpy({ guardGlobals: 'throw' })` names the file; then `mockValueProp` |
3382
+ | a block of files reported as failed suites with no stack, and zero failing tests | a test left an own enumerable key on `Object.prototype`; `mergeHooks` spreads it and collection dies | `setupAutoSpy()` guards it by default; `prototypePollution` tunes the reaction |
3383
+ | `expected [ { at: 1, …(5) }, …(8) ] to deeply equal [ { …(6) }, … ]` | one field moved in every element — usually a frozen clock or an id | `expect(diffByField(actual, expected)).toBeUndefined()` |
3384
+ | a hand-tuned number of turns waiting for a `resource()` to load | a resource needs a change-detection **tick**, not event-loop turns; `flushEventLoopUntil` never ticks and the resource never even issues its request | `flushEffects()`, flush the request, then `await settleResource(r, { label })` |
3385
+ | a `resource()` assertion that passes but reads the **default** value | the spec asserted before the resource left `loading` | `await settleResource(r, { label })` — it fails loudly instead |
3386
+ | `settleResource: … never started — its status is 'idle'` | the `params()` / `request()` computation returned `undefined`, so the loader never ran and `value()` is still the default | set the signal that computation reads, `flushEffects()`, then await again — or `{ allowIdle: true }` when idle is the state under assertion |
3387
+ | a spec dying on the runner's 5 s file timeout right after `await stable(fixture)` | the fixture never stabilised — an unflushed request, a real `setInterval` | `stable` now fails at 2000 ms naming the cause; raise `{ timeout }` only once neither is true |
3388
+ | `flushEventLoopUntil` timing out on the **first** such test only, the rest green | a cold dynamic `import()` outran the turn budget; later tests hit the module cache | `await settleDynamicImport(() => import('…'))` — await the module, do not count turns |
3389
+ | `Expected to be running in 'ProxyZone', but it was not found` | `zone.js/testing` patches jasmine/mocha/jest, not Vitest | `import 'vitest-auto-spy/zone'` after zone.js, with `globals: true` (§14) |
3390
+ | `nextWith` demanding `HttpEvent<T>` on a generated API client | `Parameters`/`ReturnType` read the **last** overload | `asSpy<Client, { overload: 'first' }>(…)`, or `Overload<M, 0>` — never `@ts-expect-error`, which `no-ts-expect-error-on-double` reports (§16) |
3391
+ | `NG0303` / `NG0304` / nothing at all, from a directive spec | the host is `standalone: false`, or the module is in the TestBed | `createDirectiveHost({ template, scope: [Module] })` (§13) |
3392
+ | `setInputs: … declares no input named …` | the key is not an input of that component — a typo, an input renamed since, or one of its own fields | set the names the message lists; a signal the component owns is moved through the signal (§13) |
3393
+ | `TS2540: Cannot assign to 'X' because it is a read-only property` | a `readonly` field of an object under test | `mockValueProp(obj, 'X', value)` — on a class **getter**, `mockReadonlyProp` |
3394
+ | `TypeError: Cannot read properties of undefined (reading 'mockReturnValue')` | the member is an **instance field**, not on the prototype — `Router.currentNavigation` since Angular 20 | `provideAutoSpy(Router, { instanceMethodsToSpyOn: ['currentNavigation'] })` (§5) |
3395
+ | `throwWith` reaching the success branch first, with the previous test's value | the spy's `ReplaySubject(1)` outlived the test that filled it | upgrade; and `resetAutoSpy(spy)` in `beforeEach` when the TestBed is built in `beforeAll` |
3396
+ | `TS2540` on a `Spy<T>` / `createAutoMock` member, which the runtime writes fine | `Spy<T>` is homomorphic and keeps the `readonly` of the source member — deliberately: on a member replaced by a **spied accessor** the assignment reaches the setter spy and the getter still answers `undefined`, so the type error is the loud version of a silent no-op | `mockValueProp(spy, 'X', value)` — it defines rather than assigns, so it works in both cases; `Mutable<Spy<T>>` is the opt-in for plain data members, and `Reflect.set` is **not** a way round it |
3397
+ | `TS2345` from `mockReturnValue` / `mockImplementation` / `mockResolvedValue` on a double that used to compile | the mock surface is `MockInstance<Method>`, so the stub is now checked against the method's own return type | stub with what the method returns; if the double is meant to answer something else, the method's type or the spec's expectation is wrong |
3398
+ | `delete mock.optionalMethod` leaving the member present and truthy | the Proxy had no `deleteProperty` trap before 3.5.0 | upgrade; before that, `mock.optionalMethod = undefined` |
3399
+ | half a double's methods reaching the real implementation after `Object.assign` | `ownKeys` on a type-driven Proxy lists only the keys already read | `createSpyFromClass(X)` — a real object, with enumerable method keys |
3400
+ | `let s: MockInstance<() => unknown>` not matching anything | `MockInstance<F>` is invariant in `F`; Jest's `SpyInstance` was not | `MockInstance<T['method']>`, or better `injectSpy(X).method` |
3401
+ | two runs with the same totals, one of them missing a suite | a lost `describe` and a fixed flake cancel out in the counters | `compareTestRuns(before, after)` — compare the set of names, not the numbers |
3402
+ | a 30 s timeout, in a different file each run | module-level `vi.fn()` in a fixture shared by files | make the fixture a factory (§10) |
3403
+ | a component's `afterNextRender` state is empty | `detectChanges()` does not run the after-render phase | `await stable(fixture)` (§11) |
3404
+ | a green test whose only line about a call is `spy.m.calledWith(1);` | that is a **stub**, not an assertion — chai's `expect(fn).to.have.been.calledWith(x)` is the one that checks | continue the chain, or `expect(spy.m).toHaveBeenCalledWith(1)` — `no-bare-called-with` (§16) |
3405
+ | `--detect-async-leaks` reporting no leaks in a suite that visibly leaks timers | `setupAutoSpy({ strayTimers: true })` cancelled them before Vitest collected | the warning on stderr says how many were taken and where the first three were scheduled; `onStrayTimers` gets every one in `timers` (§10) |
3406
+ | `createNestUnit(X): parameter #n of Y is typed as \`Object\``(or`undefined — usually a circular import`) | the compiler emitted no runtime class for that parameter — interface, union, primitive, or a circular import | `@Inject(TOKEN)` plus a `providers` entry, or `@Optional()` to receive `undefined`; `@Inject(forwardRef(() => X))` for the import cycle |
3407
+ | `createNestUnit(X): Y declares n constructor parameter(s) but carries no design:paramtypes metadata` | no `emitDecoratorMetadata` (esbuild / Vite), or `reflect-metadata` loaded after the class | tsc or SWC with `decoratorMetadata`, `@Injectable()`, `reflect-metadata` first; or `@Inject(X)` on every parameter |
3408
+ | `createNestUnit(X): A -> B -> A is a cycle among the classes built for real` | two exposed / `useClass` classes depend on each other; the helper does not resolve `forwardRef` cycles | expose one side less, or provide it |
3409
+ | `createNestUnit(X).spies.get(Y): the unit never asked for that token` | same guard as `createWithAutoSpies` — the spy would not be the one the unit uses | stub the token the unit actually injects (the message lists the auto-spied ones) |
3410
+ | `createNestUnit(X).spies.get(Y): Y is in \`expose\`, so the unit got a real instance` | an exposed class is real, not a spy | read the spies of its own collaborators, or drop it from `expose` |
3411
+ | `expect(component.ngOnInit).toHaveBeenCalled()` fails after `fixture.detectChanges()`, or a hook's `.mockImplementation` never runs | the spy was put on the **instance**; a view calls the hook it read off the class prototype when the component was created | `vi.spyOn(Cls.prototype, 'ngOnInit')` before `TestBed.createComponent`, or assert what the hook does — `no-instance-lifecycle-spy` (§16) |
3412
+ | `TS2345: Argument of type 'InjectionToken<X>' is not assignable to parameter of type 'ClassType<unknown>'`, on `registerAutoSpyDefaults` | the core entry's `registerAutoSpyDefaults` takes a class only — it may not name Angular's token type | import `registerAutoSpyDefaults` (and `clearAutoSpyDefaults`) from `vitest-auto-spy/angular`, which also takes an `InjectionToken` (§5) |
3413
+ | `selfReturning names 'x', which is not a spied method` | the name is not a method of the double — a typo, or a restricting `onlyMethodsToSpyOn` left it out; on a type-driven double, `then` and `constructor` are never spies | fix the name or the whitelist; the value is silently never returned otherwise (§5) |
3414
+ | a spec green over a `useValue` fixture whose key the code never reads — `queryParams$` on an `ActivatedRoute` | `useValue` is `any`, so a renamed or misspelled key of an object literal compiles | the member's real name — `no-unknown-use-value-key` (§16), with type information; or `provideAutoSpy(X, { overrides })`, which the compiler checks |
3415
+ | a spec runs down the "browser" (or any flag-on) branch whatever its `useValue` says | `{ provide: IS_BROWSER, useValue: {} }` for an `InjectionToken<boolean>` — `useValue` is `any`, and an object is truthy | a value of the token's type (`useValue: false`) — `no-mistyped-use-value` (§16), with type information |
3416
+ | `no request matched …` (with the requests that were made listed) | the URL, verb or predicate does not describe anything the code under test sent, or nothing subscribed | read the list in the message — it is the requests that were actually made; then fix the URL, add `{ method }`, or subscribe (§13) |
3417
+ | `this TestBed has no HttpTestingController` | `expectRequest` / `expectNoRequest` on a module that never got the testing backend | `TestBed.configureTestingModule({ providers: [...provideHttpTesting()] })` from `vitest-auto-spy/angular-http` (§13) |
3418
+ | `the test ended with N unanswered request(s)` | `provideHttpTesting({ verifyOnTeardown })` found a request the spec never flushed | answer it (`await expectRequest(url).flush(body)`), assert its absence (`expectNoRequest(url)`), or `{ verifyOnTeardown: false }` (§13) |
3419
+ | `injectActivatedRoute(): nothing provides ActivatedRoute here` | no `ActivatedRoute` provider in the injector it read | `provideActivatedRoute({ … })` from `vitest-auto-spy/angular-router` in `providers`; `injectActivatedRoute(fixture.debugElement.injector)` for a component-level one (§13) |
3420
+ | `the ActivatedRoute here is … not one provideActivatedRoute() built` | a later provider of `ActivatedRoute` won — `provideRouter()`, `RouterModule`, a `useValue`, `provideAutoSpy(ActivatedRoute)` | list `provideActivatedRoute()` last, or drop the other provider (§13) |
3421
+ | `provideActivatedRoute: the installed @angular/router does not wire ActivatedRoute …` | a router major builds `ActivatedRoute` with different internal constructors | report it with the `@angular/router` version; provide the route by hand until then (§13) |
3422
+ | `provideRouterDouble: the Router double has no …` | the code under test reached for a `Router` member the double does not cover — `isActive`, `resetConfig`, `lastSuccessfulNavigation` | the double covers `url`, `events`, `navigate`, `navigateByUrl`, `createUrlTree`, `serializeUrl`, `parseUrl`, `routerState` and `currentNavigation` / `getCurrentNavigation()`; past that, a real `provideRouter([])` with `RouterTestingHarness` (§13) |
3423
+ | `injectRouterDouble(): the Router here is Angular's own …` | `Router` is `providedIn: 'root'`, so a `TestBed` without the double hands out a real one | add `provideRouterDouble({ … })` from `vitest-auto-spy/angular-router` to `providers` (§13) |
3082
3424
 
3083
3425
  **Seven of these are library defects, not spec ones.** On anything below 3.8.0, upgrade and change
3084
3426
  nothing in the spec: `of(double)` never emitting; `accessorSpies.setters.X` still `undefined` after
@@ -3103,61 +3445,62 @@ diagnostic and is free to change: print it, never assert on it.
3103
3445
 
3104
3446
  ## 18. Do not write this
3105
3447
 
3106
- | ❌ | ✅ |
3107
- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
3108
- | `import … from 'jest-auto-spies'` | `import … from 'vitest-auto-spy'` |
3109
- | `vitest-auto-spy` inside a `bun test` file | `vitest-auto-spy/bun` |
3110
- | `let s: MyService = createSpyFromClass(MyService)` | `let s: Spy<MyService> = …` |
3111
- | `createSpyFromClass(X) as unknown as X` | `asInstance(createSpyFromClass(X))` |
3112
- | `{ provide: X, useValue: { a: vi.fn(), b: vi.fn() } }` | `provideAutoSpy(X)` |
3113
- | `{ provide: ActivatedRoute, useValue: { snapshot: { params } } }` | `provideActivatedRoute({ params })` — streams and snapshot from one record |
3114
- | `vi.spyOn(TestBed.inject(X), 'method')` | `injectSpy(X).method` |
3115
- | `vi.spyOn(component, 'ngOnInit')` after `createComponent` | `vi.spyOn(Cls.prototype, 'ngOnInit')` before it, or assert the effect |
3116
- | `{ provide: IS_BROWSER, useValue: {} }` for an `InjectionToken<boolean>` | `useValue: false` — a value of the type the token declares |
3117
- | `Object.defineProperty(service, 'ready', { value: true })` | `mockReadonlyProp(service, 'ready', true)` |
3118
- | `source$.subscribe(v => expect(v).toBe(1))` | `await expect(expectEmission(source$)).resolves.toBe(1)` |
3119
- | `await lastValueFrom(done$, { defaultValue: undefined })` | `await expectCompletion(done$)` |
3120
- | `{ timeout: 0 }` on every helper because timers are faked | `setEmissionTimeout(100)` once, in the setup file |
3121
- | `{ provide: AbstractToken, useValue: createAutoMock<T>() }` | `provideAutoSpy(AbstractToken)` |
3122
- | `mockDeep<T>()` for a chain that goes through a **call** | `mockDeep<T>({}, { selfReturning: true })` |
3123
- | `await expect(expectEmission(x$)).rejects.toBe(originalError)` | `await expect(expectError(x$)).resolves.toBe(originalError)` |
3124
- | `source$.pipe(skip(1))` / `pipe(filter(p))` in front of the helper | `expectEmission(source$, { skip: 1 })` / `{ until: p }` |
3125
- | hold the promise, `vi.runAllTimers()`, then await | `expectEmission(source$, { advance: () => vi.runAllTimers() })` |
3126
- | `injectSpy(X)` then a `mockReturnValue` per method in `beforeEach` | `provideAutoSpy(X, { returns: { … }, overrides: { … } })` |
3127
- | a local `injectSpy` wrapper with `as never` + `as Spy<T>` | the library's — it also takes an `InjectionToken` |
3128
- | a hand-written double for a token with `Observable` members | `provideAutoSpyForToken(T, undefined, { observablePropsToSpyOn: […] })` |
3129
- | `mockDeep<T>() as unknown as T` to satisfy an API typed against `T` | `asInstance(mockDeep<T>())` |
3130
- | `from([double])` to stop `of(double)` swallowing the double | `of(double)` — `schedule` is no longer answered (§2) |
3131
- | `spy.instanceField.mockReturnValue(…)` on a member Angular moved | `provideAutoSpy(X, { instanceMethodsToSpyOn: ['…'] })` (§5) |
3132
- | `expect(component.total).toBeTruthy()` (a signal) | `expect(component.total).toHaveSignalValue(3)` |
3133
- | `fixture.detectChanges()` then assert signal state | `await stable(fixture)` then assert |
3134
- | `onlyMethodsToSpyOn: [...]` "to add a method" | omit it, or use `instanceMethodsToSpyOn` |
3135
- | a `vi.fn()` the code calls with `new` | `createSpyClass(Foo)` / `mockConstructor(factory)` |
3136
- | an exported `const` fixture holding `vi.fn()`s | an exported **factory** that returns it (§10) |
3137
- | `let s: Mocked<MyService>` (Vitest's own type) | `let s: Spy<MyService>` |
3138
- | `it('x', (done) => …)` / `beforeEach((done) => …)` | `async` + `await` — Vitest passes a `TestContext`, not `done` |
3139
- | `{ ...modelInstance, flag: true }` (drops every getter) | `withOverrides(modelInstance, { flag: true })` |
3140
- | `if ('params' in link) … else throw` in every spec | `narrow.byKey(link, 'params')` |
3141
- | five `asInstance(...)` in one call | `...asInstances(a, b, c, d, e)` |
3142
- | `vi.stubGlobal('Image', vi.fn(() => ({ src: '' })))` | `stubConstructor(globalThis, 'Image', () => ({ src: '' }))` |
3143
- | `Object.defineProperty(document, 'cookie', { value })` | `mockValueProp(document, 'cookie', value)` |
3144
- | `vi.spyOn(globalThis, 'Date')` | `mockSystemTime('2025-04-30T00:00:00Z')` |
3145
- | ten `await Promise.resolve()` for a dynamic `import()` | `await settleDynamicImport(() => import('…'))` |
3146
- | `await fixture.whenRenderingDone()` | `await stable(fixture)` |
3147
- | an exported `const` provider with `vi.fn()` inside | an exported **factory** returning it (§10) |
3148
- | `.overrideProvider(X, provideAutoSpy(X))` (works, but says the wrong thing) | `.overrideProvider(X, overrideAutoSpy(X))` |
3149
- | `TestBed.overrideComponent` to swap a provider | `overrideComponentProvider(Cmp, X)` |
3150
- | `{ target, isIntersecting } as unknown as IntersectionObserverEntry` | `intersectionEntry(target, true)` |
3151
- | `@Component({ selector: 'app-chart' }) class MockChartComponent { @Input() … }` | `createComponentStub(ChartComponent)` — the selector cannot drift |
3152
- | a `TestingStorage` class assigned to `globalThis.localStorage` | `stubWebStorage('localStorage')`, restored with the other patches |
3153
- | an assertion containing a date, with no clock set | `mockSystemTime(iso)` first |
3154
- | `configureTestingModule` inside every `it()` | one per `describe` |
3155
- | `vi.mock('@angular/core')` to neutralise `effect()` | set the signals, `await stable(fixture)`, assert the result |
3156
- | a second `vi.spyOn(console, 'error')` | `consoleErrorSpy` from `vitest-auto-spy/console`, installed with `installConsoleSpies()` |
3157
- | `import { consoleErrorSpy } from 'vitest-auto-spy/console'` as the install | `installConsoleSpies()` in `beforeEach`, `restoreConsole()` in `afterEach` — the import installs once per worker |
3158
- | a bare `vi.spyOn(console, 'error')` to keep a spec quiet | `.mockImplementation(() => undefined)` — without it the line still prints |
3159
- | `mockReadonlyProp(c, 'items', vi.fn(() => []))` | `mockReadonlyProp(c, 'items', signal([]))` — a real signal |
3160
- | `spy.m.mockReturnValue(subject$)` for a `vi.fn(() => subject$)` | `spy.m.mockImplementation(() => subject$)` — the variable is re-read |
3448
+ | ❌ | ✅ |
3449
+ | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
3450
+ | `import … from 'jest-auto-spies'` | `import … from 'vitest-auto-spy'` |
3451
+ | `vitest-auto-spy` inside a `bun test` file | `vitest-auto-spy/bun` |
3452
+ | `let s: MyService = createSpyFromClass(MyService)` | `let s: Spy<MyService> = …` |
3453
+ | `createSpyFromClass(X) as unknown as X` | `asInstance(createSpyFromClass(X))` |
3454
+ | `{ provide: X, useValue: { a: vi.fn(), b: vi.fn() } }` | `provideAutoSpy(X)` |
3455
+ | `{ provide: ActivatedRoute, useValue: { snapshot: { params } } }` | `provideActivatedRoute({ params })` — streams and snapshot from one record |
3456
+ | `createAutoMock<Router>({ events: of(), url: '/' }, { returns: { navigate } })` | `provideRouterDouble({ url })` — one URL behind `url`, `routerState` and `events` |
3457
+ | `vi.spyOn(TestBed.inject(X), 'method')` | `injectSpy(X).method` |
3458
+ | `vi.spyOn(component, 'ngOnInit')` after `createComponent` | `vi.spyOn(Cls.prototype, 'ngOnInit')` before it, or assert the effect |
3459
+ | `{ provide: IS_BROWSER, useValue: {} }` for an `InjectionToken<boolean>` | `useValue: false` — a value of the type the token declares |
3460
+ | `Object.defineProperty(service, 'ready', { value: true })` | `mockReadonlyProp(service, 'ready', true)` |
3461
+ | `source$.subscribe(v => expect(v).toBe(1))` | `await expect(expectEmission(source$)).resolves.toBe(1)` |
3462
+ | `await lastValueFrom(done$, { defaultValue: undefined })` | `await expectCompletion(done$)` |
3463
+ | `{ timeout: 0 }` on every helper because timers are faked | `setEmissionTimeout(100)` once, in the setup file |
3464
+ | `{ provide: AbstractToken, useValue: createAutoMock<T>() }` | `provideAutoSpy(AbstractToken)` |
3465
+ | `mockDeep<T>()` for a chain that goes through a **call** | `mockDeep<T>({}, { selfReturning: true })` |
3466
+ | `await expect(expectEmission(x$)).rejects.toBe(originalError)` | `await expect(expectError(x$)).resolves.toBe(originalError)` |
3467
+ | `source$.pipe(skip(1))` / `pipe(filter(p))` in front of the helper | `expectEmission(source$, { skip: 1 })` / `{ until: p }` |
3468
+ | hold the promise, `vi.runAllTimers()`, then await | `expectEmission(source$, { advance: () => vi.runAllTimers() })` |
3469
+ | `injectSpy(X)` then a `mockReturnValue` per method in `beforeEach` | `provideAutoSpy(X, { returns: { … }, overrides: { … } })` |
3470
+ | a local `injectSpy` wrapper with `as never` + `as Spy<T>` | the library's — it also takes an `InjectionToken` |
3471
+ | a hand-written double for a token with `Observable` members | `provideAutoSpyForToken(T, undefined, { observablePropsToSpyOn: […] })` |
3472
+ | `mockDeep<T>() as unknown as T` to satisfy an API typed against `T` | `asInstance(mockDeep<T>())` |
3473
+ | `from([double])` to stop `of(double)` swallowing the double | `of(double)` — `schedule` is no longer answered (§2) |
3474
+ | `spy.instanceField.mockReturnValue(…)` on a member Angular moved | `provideAutoSpy(X, { instanceMethodsToSpyOn: ['…'] })` (§5) |
3475
+ | `expect(component.total).toBeTruthy()` (a signal) | `expect(component.total).toHaveSignalValue(3)` |
3476
+ | `fixture.detectChanges()` then assert signal state | `await stable(fixture)` then assert |
3477
+ | `onlyMethodsToSpyOn: [...]` "to add a method" | omit it, or use `instanceMethodsToSpyOn` |
3478
+ | a `vi.fn()` the code calls with `new` | `createSpyClass(Foo)` / `mockConstructor(factory)` |
3479
+ | an exported `const` fixture holding `vi.fn()`s | an exported **factory** that returns it (§10) |
3480
+ | `let s: Mocked<MyService>` (Vitest's own type) | `let s: Spy<MyService>` |
3481
+ | `it('x', (done) => …)` / `beforeEach((done) => …)` | `async` + `await` — Vitest passes a `TestContext`, not `done` |
3482
+ | `{ ...modelInstance, flag: true }` (drops every getter) | `withOverrides(modelInstance, { flag: true })` |
3483
+ | `if ('params' in link) … else throw` in every spec | `narrow.byKey(link, 'params')` |
3484
+ | five `asInstance(...)` in one call | `...asInstances(a, b, c, d, e)` |
3485
+ | `vi.stubGlobal('Image', vi.fn(() => ({ src: '' })))` | `stubConstructor(globalThis, 'Image', () => ({ src: '' }))` |
3486
+ | `Object.defineProperty(document, 'cookie', { value })` | `mockValueProp(document, 'cookie', value)` |
3487
+ | `vi.spyOn(globalThis, 'Date')` | `mockSystemTime('2025-04-30T00:00:00Z')` |
3488
+ | ten `await Promise.resolve()` for a dynamic `import()` | `await settleDynamicImport(() => import('…'))` |
3489
+ | `await fixture.whenRenderingDone()` | `await stable(fixture)` |
3490
+ | an exported `const` provider with `vi.fn()` inside | an exported **factory** returning it (§10) |
3491
+ | `.overrideProvider(X, provideAutoSpy(X))` (works, but says the wrong thing) | `.overrideProvider(X, overrideAutoSpy(X))` |
3492
+ | `TestBed.overrideComponent` to swap a provider | `overrideComponentProvider(Cmp, X)` |
3493
+ | `{ target, isIntersecting } as unknown as IntersectionObserverEntry` | `intersectionEntry(target, true)` |
3494
+ | `@Component({ selector: 'app-chart' }) class MockChartComponent { @Input() … }` | `createComponentStub(ChartComponent)` — the selector cannot drift |
3495
+ | a `TestingStorage` class assigned to `globalThis.localStorage` | `stubWebStorage('localStorage')`, restored with the other patches |
3496
+ | an assertion containing a date, with no clock set | `mockSystemTime(iso)` first |
3497
+ | `configureTestingModule` inside every `it()` | one per `describe` |
3498
+ | `vi.mock('@angular/core')` to neutralise `effect()` | set the signals, `await stable(fixture)`, assert the result |
3499
+ | a second `vi.spyOn(console, 'error')` | `consoleErrorSpy` from `vitest-auto-spy/console`, installed with `installConsoleSpies()` |
3500
+ | `import { consoleErrorSpy } from 'vitest-auto-spy/console'` as the install | `installConsoleSpies()` in `beforeEach`, `restoreConsole()` in `afterEach` — the import installs once per worker |
3501
+ | a bare `vi.spyOn(console, 'error')` to keep a spec quiet | `.mockImplementation(() => undefined)` — without it the line still prints |
3502
+ | `mockReadonlyProp(c, 'items', vi.fn(() => []))` | `mockReadonlyProp(c, 'items', signal([]))` — a real signal |
3503
+ | `spy.m.mockReturnValue(subject$)` for a `vi.fn(() => subject$)` | `spy.m.mockImplementation(() => subject$)` — the variable is re-read |
3161
3504
 
3162
3505
  **The one mechanical rename in a migration that is not equivalent.** `vi.fn(() => x)` reads `x`
3163
3506
  when the double is _called_; `mockReturnValue(x)` freezes the value `x` had when the double was
@@ -3218,7 +3561,7 @@ Full reference: <https://asdalexey.github.io/vitest-auto-spy/utilities/cli>.
3218
3561
  ### If you were asked why a suite is slow
3219
3562
 
3220
3563
  ```bash
3221
- npx vitest-auto-spy perf # runs the suite once and reports; always exits 0
3564
+ npx vitest-auto-spy perf # runs the suite once and reports; exits 0 without --gate
3222
3565
  npx vitest-auto-spy perf src/some/dir # a path is passed through to Vitest as a file filter
3223
3566
  ```
3224
3567
 
@@ -3252,6 +3595,37 @@ is the default, resident memory measured at 1.42 GB plus ~155 MB per worker, and
3252
3595
  about 2.8 % of wall clock. Do not quote a worker count as universally right — it is a property of
3253
3596
  the machine.
3254
3597
 
3598
+ **A bare `vitest run` is not every repository's suite, and `perf` refuses to pretend otherwise.**
3599
+ Where the suite is assembled by something else — an Angular builder, an Nx target, a script that
3600
+ generates a config per project — there is no root `vite(st).config.*`, the Vitest defaults sweep up
3601
+ every `*.spec.*` in the tree with no globals and no aliases, and every file fails to collect. The
3602
+ phase table that comes out of that is real seconds spent on nothing: measured on one such workspace,
3603
+ 1 830 files, 29 s of wall clock and **zero** test bodies executed. `perf` checks for that shape
3604
+ before it runs anything, and refuses any report in which no body finished (exit 2). Measure the
3605
+ repository's own command instead:
3606
+
3607
+ ```bash
3608
+ npx vitest-auto-spy perf --command 'npm test' # measure that command
3609
+ npx vitest-auto-spy perf --command 'npm test -- {paths:--include=}' --gate
3610
+ ```
3611
+
3612
+ `--command` puts `VITEST_AUTO_SPY_PERF_OUT` and `VITEST_AUTO_SPY_PERF_REPORTER` in that command's
3613
+ environment; the configuration it reaches attaches the reporter itself (`reporters: perf ===
3614
+ undefined ? ['default'] : ['default', perf]`), and the reporter writes nothing at all when the first
3615
+ variable is unset, so it can be declared permanently. `{paths}` / `{paths:<prefix>}` is where the
3616
+ files of a confirmation pass go.
3617
+
3618
+ **`--gate` is the only part of this command that fails anything**, and three rules keep it honest.
3619
+ It judges the `tests` phase alone, because the other five are the harness and the machine rather than
3620
+ anybody's code. A file is over budget only when it is over both an absolute floor and `--factor` ×
3621
+ the median file **of the same run**, which is what makes the verdict the same on a loaded CI runner
3622
+ and on an idle laptop. And every candidate is re-measured on its own before it may fail anything: a
3623
+ file that is fast when it has the machine to itself is reported as _not reproduced_, an `info` rather
3624
+ than a finding. Without a way to re-measure, findings are warnings that fail nothing unless
3625
+ `--no-confirm` says one reading is enough. Exit `1` is "over budget", exit `2` is "there was nothing
3626
+ to judge" — including a red suite, which the gate will not judge at all, since a failed test is
3627
+ measured until its timeout and 30 s of timeout looks exactly like 30 s of slow code.
3628
+
3255
3629
  `--json <path>` re-analyses a report an earlier `--out <path>` run wrote, instead of running Vitest
3256
3630
  again. Full reference: <https://asdalexey.github.io/vitest-auto-spy/utilities/cli>.
3257
3631