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

zoneful-integration.test.ts

191 lines5.6 KB

1// cspell:ignore zoneful
2import {
3 ApplicationRef,
4 Component,
5 NgZone,
6 provideZoneChangeDetection,
7 signal,
8} from '@angular/core'
9import { TestBed } from '@angular/core/testing'
10import { afterEach, beforeEach, describe, expect, it } from 'vitest'
11import { provideIsRestoring } from '../internal'
12import {
13 QueryClient,
14 injectMutation,
15 injectQueries,
16 injectQuery,
17 provideTanStackQuery,
18} from '..'
19​
20/**
21 * These tests deliberately provide Angular's zone-based scheduler directly.
22 * They are run by vitest.zoneful.config.ts, whose setup also loads the Zone.js
23 * testing patches. Keeping this small integration set separate avoids making
24 * every signal assertion in the zoneless suite depend on Zone.js scheduling.
25 */
26describe('Zone.js notification integration', () => {
27 let queryClient: QueryClient
28​
29 beforeEach(() => {
30 queryClient = new QueryClient()
31 TestBed.configureTestingModule({
32 providers: [
33 provideZoneChangeDetection(),
34 provideTanStackQuery(() => queryClient),
35 ],
36 })
37 })
38​
39 afterEach(() => {
40 TestBed.resetTestingModule()
41 })
42​
43 it('keeps an injectQuery signal current after its subscription commits', () => {
44 const key = ['zoneful-query']
45 const query = TestBed.runInInjectionContext(() =>
46 injectQuery(() => ({
47 queryKey: key,
48 enabled: false,
49 })),
50 )
51​
52 expect(query.data()).toBeUndefined()
53 TestBed.tick()
54 queryClient.setQueryData(key, 'updated')
55​
56 expect(query.data()).toBe('updated')
57 })
58​
59 it('keeps injectQueries current after its subscription commits', () => {
60 const key = ['zoneful-queries']
61 const queries = TestBed.runInInjectionContext(() =>
62 injectQueries(() => ({
63 queries: [{ queryKey: key, enabled: false }],
64 })),
65 )
66​
67 expect(queries()[0].data()).toBeUndefined()
68 TestBed.tick()
69 queryClient.setQueryData(key, 'updated')
70​
71 expect(queries()[0].data()).toBe('updated')
72 })
73​
74 it('makes committed query notifications visible inside mutation onMutate', async () => {
75 const key = ['zoneful-optimistic']
76 const query = TestBed.runInInjectionContext(() =>
77 injectQuery(() => ({
78 queryKey: key,
79 enabled: false,
80 })),
81 )
82 const seenInOnMutate: Array<string | undefined> = []
83 const mutation = TestBed.runInInjectionContext(() =>
84 injectMutation(() => ({
85 mutationKey: ['zoneful-mutation'],
86 mutationFn: async () => 'server',
87 onMutate: () => {
88 queryClient.setQueryData(key, 'optimistic')
89 seenInOnMutate.push(query.data() as string | undefined)
90 },
91 })),
92 )
93​
94 query.data()
95 TestBed.tick()
96 await mutation.mutateAsync()
97​
98 expect(seenInOnMutate).toEqual(['optimistic'])
99 })
100​
101 it('uses the latest options when restoration ends in the same Zone.js turn', async () => {
102 const isRestoring = signal(true)
103 const key = signal('old')
104 const queriedKeys: Array<string> = []
105​
106 TestBed.resetTestingModule()
107 TestBed.configureTestingModule({
108 providers: [
109 provideZoneChangeDetection(),
110 provideTanStackQuery(() => queryClient),
111 provideIsRestoring(() => isRestoring.asReadonly()),
112 ],
113 })
114​
115 const query = TestBed.runInInjectionContext(() =>
116 injectQuery(() => ({
117 queryKey: ['zoneful-restoration', key()],
118 queryFn: ({ queryKey }) => {
119 const currentKey = queryKey[1] as string
120 queriedKeys.push(currentKey)
121 return Promise.resolve(currentKey)
122 },
123 })),
124 )
125​
126 expect(query.status()).toBe('pending')
127 key.set('new')
128 isRestoring.set(false)
129 TestBed.tick()
130 await TestBed.inject(ApplicationRef).whenStable()
131​
132 expect(queriedKeys).toEqual(['new'])
133 expect(query.data()).toBe('new')
134 expect(
135 queryClient
136 .getQueryCache()
137 .find({ queryKey: ['zoneful-restoration', 'new'] })
138 ?.getObserversCount(),
139 ).toBe(1)
140 })
141​
142 it('completes dependent queries before application stability without manual effect flushing', async () => {
143 @Component({ template: '{{ second.data() }}' })
144 class Page {
145 first = injectQuery(() => ({
146 queryKey: ['zoneful-dependency-first'],
147 queryFn: async () => 'ready',
148 }))
149 second = injectQuery(() => ({
150 queryKey: ['zoneful-dependency-second'],
151 enabled: this.first.isSuccess(),
152 queryFn: async () => 'dependent data',
153 }))
154 }
155​
156 const fixture = TestBed.createComponent(Page)
157 fixture.autoDetectChanges()
158 await TestBed.inject(ApplicationRef).whenStable()
159 expect(fixture.componentInstance.second.data()).toBe('dependent data')
160 })
161 it('renders outside-zone query, multi-query and mutation notifications automatically', async () => {
162 @Component({
163 template:
164 '{{ query.data() }} / {{ queries()[0].data() }} / {{ mutation.status() }}',
165 })
166 class Page {
167 query = injectQuery(() => ({
168 queryKey: ['outside-single'],
169 enabled: false,
170 }))
171 queries = injectQueries(() => ({
172 queries: [{ queryKey: ['outside-multiple'], enabled: false }],
173 }))
174 mutation = injectMutation(() => ({ mutationFn: async () => 'done' }))
175 }
176 const fixture = TestBed.createComponent(Page)
177 fixture.autoDetectChanges()
178 await fixture.whenStable()
179 const zone = TestBed.inject(NgZone)
180 const promise = zone.runOutsideAngular(() => {
181 queryClient.setQueryData(['outside-single'], 'single')
182 queryClient.setQueryData(['outside-multiple'], 'multiple')
183 return fixture.componentInstance.mutation.mutateAsync()
184 })
185 await promise
186 await fixture.whenStable()
187 expect(fixture.nativeElement.textContent).toBe(
188 'single / multiple / success',
189 )
190 })
191})