Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

test-utils.ts

100 lines2.7 KB

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