Open History to see the last commit
1import {
2 isSignal,
3 provideZonelessChangeDetection,
4 untracked,
5} from '@angular/core'
6import { TestBed } from '@angular/core/testing'
7import { expect, vi } from 'vitest'
8import { provideTanStackQuery } from '..'
9import type { QueryClient } from '@tanstack/query-core'
10import type {
11 EnvironmentProviders,
12 Provider,
13 Signal,
14 Type,
15} from '@angular/core'
16
17// cspell:ignore ɵcmp ɵdir
18
19// Evaluate all signals on an object and return the result
20function evaluateSignals<T extends Record<string, any>>(
21 obj: T,
22): { [K in keyof T]: ReturnType<T[K]> } {
23 const result: Partial<{ [K in keyof T]: ReturnType<T[K]> }> = {}
24
25 untracked(() => {
26 for (const key in obj) {
27 if (
28 Object.prototype.hasOwnProperty.call(obj, key) &&
29 // Only evaluate signals, not normal functions
30 isSignal(obj[key])
31 ) {
32 const func = obj[key]
33 result[key] = func()
34 }
35 }
36 })
37
38 return result as { [K in keyof T]: ReturnType<T[K]> }
39}
40
41export const expectSignals = <T extends Record<string, any>>(
42 obj: T,
43 expected: Partial<{
44 [K in keyof T]: T[K] extends Signal<any> ? ReturnType<T[K]> : never
45 }>,
46): void => {
47 expect(evaluateSignals(obj)).toMatchObject(expected)
48}
49
50/**
51 * Reset Angular's TestBed and configure the standard TanStack Query providers for tests.
52 * Pass additional providers (including EnvironmentProviders) via the options argument.
53 */
54export function setupTanStackQueryTestBed(
55 queryClient: QueryClient,
56 options: { providers?: Array<Provider | EnvironmentProviders> } = {},
57) {
58 TestBed.resetTestingModule()
59 TestBed.configureTestingModule({
60 providers: [
61 provideZonelessChangeDetection(),
62 provideTanStackQuery(queryClient),
63 ...(options.providers ?? []),
64 ],
65 })
66}
67
68/**
69 * TanStack Query schedules notifyManager updates with setTimeout(0); when fake timers
70 * are enabled, advance them so PendingTasks sees the queued work.
71 */
72export async function flushQueryUpdates() {
73 await vi.advanceTimersByTimeAsync(0)
74}
75
76const SIGNAL_BASED_INPUT_FLAG = 1
77
78/**
79 * Register a signal-based input on a test-only component/dir so Angular marks the
80 * `input.required()` member as bound before the initial change detection run.
81 *
82 * After migrating to Angular 21 we can use the CLI to compile and run Vitest tests
83 * and this helper should be obsolete.
84 */
85export function registerSignalInput<T>(
86 type: Type<T>,
87 inputName: keyof T & string,
88) {
89 const definition = (type as any).ɵcmp ?? (type as any).ɵdir
90 if (!definition) {
91 throw new Error(`Component ${type.name} is missing its definition`)
92 }
93
94 definition.inputs = {
95 ...(definition.inputs ?? {}),
96 [inputName]: [inputName, SIGNAL_BASED_INPUT_FLAG, null],
97 }
98 definition.declaredInputs = {
99 ...(definition.declaredInputs ?? {}),
100 [inputName]: inputName,
101 }
102}