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

test-utils.ts

63 lines1.9 KB

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