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

test-utils.ts

67 lines1.9 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 { EnvironmentProviders, Provider, Signal } from '@angular/core'
11​
12// Evaluate all signals on an object and return the result
13function evaluateSignals<T extends Record<string, any>>(
14 obj: T,
15): { [K in keyof T]: ReturnType<T[K]> } {
16 const result: Partial<{ [K in keyof T]: ReturnType<T[K]> }> = {}
17​
18 untracked(() => {
19 for (const key in obj) {
20 if (
21 Object.prototype.hasOwnProperty.call(obj, key) &&
22 // Only evaluate signals, not normal functions
23 isSignal(obj[key])
24 ) {
25 const func = obj[key]
26 result[key] = func()
27 }
28 }
29 })
30​
31 return result as { [K in keyof T]: ReturnType<T[K]> }
33​
34export const expectSignals = <T extends Record<string, any>>(
35 obj: T,
36 expected: Partial<{
37 [K in keyof T]: T[K] extends Signal<any> ? ReturnType<T[K]> : never
38 }>,
39): void => {
40 expect(evaluateSignals(obj)).toMatchObject(expected)
42​
43/**
44 * Reset Angular's TestBed and configure the standard TanStack Query providers for tests.
45 * Pass additional providers (including EnvironmentProviders) via the options argument.
46 */
47export function setupTanStackQueryTestBed(
48 queryClient: QueryClient,
49 options: { providers?: Array<Provider | EnvironmentProviders> } = {},
50) {
51 TestBed.resetTestingModule()
52 TestBed.configureTestingModule({
53 providers: [
54 provideZonelessChangeDetection(),
55 provideTanStackQuery(queryClient),
56 ...(options.providers ?? []),
57 ],
58 })
60​
61/**
62 * TanStack Query schedules notifyManager updates with setTimeout(0); when fake timers
63 * are enabled, advance them so PendingTasks sees the queued work.
64 */
65export async function flushQueryUpdates() {
66 await vi.advanceTimersByTimeAsync(0)