Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpserts.test.tsx

raw
1 import { createApi } from '@reduxjs/toolkit/query/react'
2 import { createAction } from '@reduxjs/toolkit'
3 import {
4 actionsReducer,
5 hookWaitFor,
6 setupApiStore,
7 } from '../../tests/utils/helpers'
8 import {
9 render,
10 renderHook,
11 act,
12 waitFor,
13 screen,
14 } from '@testing-library/react'
15 import { delay } from 'msw'
16
17 interface Post {
18 id: string
19 title: string
20 contents: string
21 }
22
23 interface FolderT {
24 id: number
25 children: FolderT[]
26 }
27
28 const baseQuery = vi.fn()
29 beforeEach(() => baseQuery.mockReset())
30
31 const postAddedAction = createAction<string>('postAdded')
32
33 const api = createApi({
34 baseQuery: (...args: any[]) => {
35 const result = baseQuery(...args)
36 if (typeof result === 'object' && 'then' in result)
37 return result
38 .then((data: any) => ({ data, meta: 'meta' }))
39 .catch((e: any) => ({ error: e }))
40 return { data: result, meta: 'meta' }
41 },
42 tagTypes: ['Post', 'Folder'],
43 endpoints: (build) => ({
44 getPosts: build.query<Post[], void>({
45 query: () => '/posts',
46 }),
47 post: build.query<Post, string>({
48 query: (id) => `post/${id}`,
49 providesTags: ['Post'],
50 }),
51 updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
52 query: ({ id, ...patch }) => ({
53 url: `post/${id}`,
54 method: 'PATCH',
55 body: patch,
56 }),
57 async onQueryStarted(arg, { dispatch, queryFulfilled, getState }) {
58 const currentItem = api.endpoints.post.select(arg.id)(getState())
59 if (currentItem?.data) {
60 dispatch(
61 api.util.upsertQueryData('post', arg.id, {
62 ...currentItem.data,
63 ...arg,
64 }),
65 )
66 }
67 },
68 invalidatesTags: (result) => (result ? ['Post'] : []),
69 }),
70 post2: build.query<Post, string>({
71 queryFn: async (id) => {
72 await delay(20)
73 return {
74 data: {
75 id,
76 title: 'All about cheese.',
77 contents: 'TODO',
78 },
79 }
80 },
81 }),
82 postWithSideEffect: build.query<Post, string>({
83 query: (id) => `post/${id}`,
84 providesTags: (result) => {
85 if (result) {
86 return [{ type: 'Post', id: result.id } as const]
87 }
88 return []
89 },
90 async onCacheEntryAdded(arg, api) {
91 // Verify that lifecycle promise resolution works
92 const res = await api.cacheDataLoaded
93
94 // and leave a side effect we can check in the test
95 api.dispatch(postAddedAction(res.data.id))
96 },
97 keepUnusedDataFor: 0.01,
98 }),
99 getFolder: build.query<FolderT, number>({
100 queryFn: async (args) => {
101 return {
102 data: {
103 id: args,
104 // Folder contains children that are as well folders
105 children: [{ id: 2, children: [] }],
106 },
107 }
108 },
109 providesTags: (result, err, args) => [{ type: 'Folder', id: args }],
110 onQueryStarted: async (args, queryApi) => {
111 const { data } = await queryApi.queryFulfilled
112
113 // Upsert getFolder endpoint with children from response data
114 const upsertData = data.children.map((child) => ({
115 arg: child.id,
116 endpointName: 'getFolder' as const,
117 value: child,
118 }))
119
120 queryApi.dispatch(api.util.upsertQueryEntries(upsertData))
121 },
122 }),
123 }),
124 })
125
126 const storeRef = setupApiStore(api, {
127 ...actionsReducer,
128 })
129
130 describe('basic lifecycle', () => {
131 let onStart = vi.fn(),
132 onError = vi.fn(),
133 onSuccess = vi.fn()
134
135 const extendedApi = api.injectEndpoints({
136 endpoints: (build) => ({
137 test: build.mutation({
138 query: (x) => x,
139 async onQueryStarted(arg, api) {
140 onStart(arg)
141 try {
142 const result = await api.queryFulfilled
143 onSuccess(result)
144 } catch (e) {
145 onError(e)
146 }
147 },
148 }),
149 }),
150 overrideExisting: true,
151 })
152
153 beforeEach(() => {
154 onStart.mockReset()
155 onError.mockReset()
156 onSuccess.mockReset()
157 })
158
159 test('Does basic inserts and upserts', async () => {
160 const newPost: Post = {
161 id: '3',
162 contents: 'Inserted content',
163 title: 'Inserted title',
164 }
165 const insertPromise = storeRef.store.dispatch(
166 api.util.upsertQueryData('post', newPost.id, newPost),
167 )
168
169 await insertPromise
170
171 const selectPost3 = api.endpoints.post.select(newPost.id)
172 const insertedPostEntry = selectPost3(storeRef.store.getState())
173 expect(insertedPostEntry.isSuccess).toBe(true)
174 expect(insertedPostEntry.data).toEqual(newPost)
175
176 const updatedPost: Post = {
177 id: '3',
178 contents: 'Updated content',
179 title: 'Updated title',
180 }
181
182 const updatePromise = storeRef.store.dispatch(
183 api.util.upsertQueryData('post', updatedPost.id, updatedPost),
184 )
185
186 await updatePromise
187
188 const updatedPostEntry = selectPost3(storeRef.store.getState())
189
190 expect(updatedPostEntry.isSuccess).toBe(true)
191 expect(updatedPostEntry.data).toEqual(updatedPost)
192 })
193
194 test('success', async () => {
195 const { result } = renderHook(
196 () => extendedApi.endpoints.test.useMutation(),
197 {
198 wrapper: storeRef.wrapper,
199 },
200 )
201
202 baseQuery.mockResolvedValue('success')
203
204 expect(onStart).not.toHaveBeenCalled()
205 expect(baseQuery).not.toHaveBeenCalled()
206 act(() => void result.current[0]('arg'))
207 expect(onStart).toHaveBeenCalledWith('arg')
208 expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
209
210 expect(onError).not.toHaveBeenCalled()
211 expect(onSuccess).not.toHaveBeenCalled()
212 await act(() => delay(5))
213 expect(onError).not.toHaveBeenCalled()
214 expect(onSuccess).toHaveBeenCalledWith({ data: 'success', meta: 'meta' })
215 })
216
217 test('error', async () => {
218 const { result } = renderHook(
219 () => extendedApi.endpoints.test.useMutation(),
220 {
221 wrapper: storeRef.wrapper,
222 },
223 )
224
225 baseQuery.mockRejectedValueOnce('error')
226
227 expect(onStart).not.toHaveBeenCalled()
228 expect(baseQuery).not.toHaveBeenCalled()
229 act(() => void result.current[0]('arg'))
230 expect(onStart).toHaveBeenCalledWith('arg')
231 expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
232
233 expect(onError).not.toHaveBeenCalled()
234 expect(onSuccess).not.toHaveBeenCalled()
235 await act(() => delay(5))
236 expect(onError).toHaveBeenCalledWith({
237 error: 'error',
238 isUnhandledError: false,
239 meta: undefined,
240 })
241 expect(onSuccess).not.toHaveBeenCalled()
242 })
243 })
244
245 describe('upsertQueryData', () => {
246 test('inserts cache entry', async () => {
247 baseQuery
248 .mockResolvedValueOnce({
249 id: '3',
250 title: 'All about cheese.',
251 contents: 'TODO',
252 })
253 // TODO I have no idea why the query is getting called multiple times,
254 // but passing an additional mocked value (_any_ value)
255 // seems to silence some annoying "got an undefined result" logging
256 .mockResolvedValueOnce(42)
257 const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {
258 wrapper: storeRef.wrapper,
259 })
260 await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
261
262 const dataBefore = result.current.data
263 expect(dataBefore).toEqual({
264 id: '3',
265 title: 'All about cheese.',
266 contents: 'TODO',
267 })
268
269 await act(async () => {
270 storeRef.store.dispatch(
271 api.util.upsertQueryData('post', '3', {
272 id: '3',
273 title: 'All about cheese.',
274 contents: 'I love cheese!',
275 }),
276 )
277 })
278
279 expect(result.current.data).not.toBe(dataBefore)
280 expect(result.current.data).toEqual({
281 id: '3',
282 title: 'All about cheese.',
283 contents: 'I love cheese!',
284 })
285 })
286
287 test('does update non-existing values', async () => {
288 baseQuery
289 // throw an error to make sure there is no cached data
290 .mockImplementationOnce(async () => {
291 throw new Error('failed to load')
292 })
293 .mockResolvedValueOnce(42)
294
295 // a subscriber is needed to have the data stay in the cache
296 // Not sure if this is the wanted behavior, I would have liked
297 // it to stay in the cache for the x amount of time the cache
298 // is preserved normally after the last subscriber was unmounted
299 const { result, rerender } = renderHook(
300 () => api.endpoints.post.useQuery('4'),
301 {
302 wrapper: storeRef.wrapper,
303 },
304 )
305 await hookWaitFor(() => expect(result.current.isError).toBeTruthy())
306
307 // upsert the data
308 act(() => {
309 storeRef.store.dispatch(
310 api.util.upsertQueryData('post', '4', {
311 id: '4',
312 title: 'All about cheese',
313 contents: 'I love cheese!',
314 }),
315 )
316 })
317
318 // rerender the hook
319 rerender()
320 // wait until everything has settled
321 await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
322
323 // the cached data is returned as the result
324 expect(result.current.data).toStrictEqual({
325 id: '4',
326 title: 'All about cheese',
327 contents: 'I love cheese!',
328 })
329 })
330
331 test('upsert while a normal query is running (success)', async () => {
332 const fetchedData = {
333 id: '3',
334 title: 'All about cheese.',
335 contents: 'Yummy',
336 }
337 baseQuery.mockImplementation(() => delay(20).then(() => fetchedData))
338 const upsertedData = {
339 id: '3',
340 title: 'Data from a SSR Render',
341 contents: 'This is just some random data',
342 }
343
344 const selector = api.endpoints.post.select('3')
345 const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3'))
346 const upsertRes = storeRef.store.dispatch(
347 api.util.upsertQueryData('post', '3', upsertedData),
348 )
349
350 await upsertRes
351 let state = selector(storeRef.store.getState())
352 expect(state.data).toEqual(upsertedData)
353
354 await fetchRes
355 state = selector(storeRef.store.getState())
356 expect(state.data).toEqual(fetchedData)
357 })
358 test('upsert while a normal query is running (rejected)', async () => {
359 baseQuery.mockImplementationOnce(async () => {
360 await delay(20)
361 // eslint-disable-next-line no-throw-literal
362 throw 'Error!'
363 })
364 const upsertedData = {
365 id: '3',
366 title: 'Data from a SSR Render',
367 contents: 'This is just some random data',
368 }
369
370 const selector = api.endpoints.post.select('3')
371 const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3'))
372 const upsertRes = storeRef.store.dispatch(
373 api.util.upsertQueryData('post', '3', upsertedData),
374 )
375
376 await upsertRes
377 let state = selector(storeRef.store.getState())
378 expect(state.data).toEqual(upsertedData)
379 expect(state.isSuccess).toBeTruthy()
380
381 await fetchRes
382 state = selector(storeRef.store.getState())
383 expect(state.data).toEqual(upsertedData)
384 expect(state.isError).toBeTruthy()
385 })
386 })
387
388 describe('upsertQueryEntries', () => {
389 const posts: Post[] = [
390 {
391 id: '1',
392 contents: 'A',
393 title: 'A',
394 },
395 {
396 id: '2',
397 contents: 'B',
398 title: 'B',
399 },
400 {
401 id: '3',
402 contents: 'C',
403 title: 'C',
404 },
405 ]
406
407 const entriesAction = api.util.upsertQueryEntries([
408 {
409 endpointName: 'getPosts',
410 arg: undefined,
411 value: posts,
412 },
413 ...posts.map((post) => ({
414 endpointName: 'postWithSideEffect' as const,
415 arg: post.id,
416 value: post,
417 })),
418 ])
419
420 test('Upserts many entries at once', async () => {
421 storeRef.store.dispatch(entriesAction)
422
423 const state = storeRef.store.getState()
424
425 expect(api.endpoints.getPosts.select()(state).data).toBe(posts)
426
427 for (const post of posts) {
428 expect(api.endpoints.postWithSideEffect.select(post.id)(state).data).toBe(
429 post,
430 )
431
432 // Should have added tags
433 expect(state.api.provided.Post[post.id]).toEqual([
434 `postWithSideEffect("${post.id}")`,
435 ])
436 }
437 })
438
439 test('Triggers cache lifecycles and side effects', async () => {
440 storeRef.store.dispatch(entriesAction)
441
442 // Tricky timing. The cache data promises will be resolved
443 // in microtasks. We need to wait for them. Best to do this
444 // in a loop just to avoid a hardcoded delay, but also this
445 // needs to complete before `keepUnusedDataFor` expires them.
446 await waitFor(
447 () => {
448 const state = storeRef.store.getState()
449
450 // onCacheEntryAdded should have run for each post,
451 // including cache data being resolved
452 for (const post of posts) {
453 const matchingSideEffectAction = state.actions.find(
454 (action) =>
455 postAddedAction.match(action) && action.payload === post.id,
456 )
457 expect(matchingSideEffectAction).toBeTruthy()
458 }
459
460 const selectedData =
461 api.endpoints.postWithSideEffect.select('1')(state).data
462
463 expect(selectedData).toBe(posts[0])
464 },
465 { timeout: 50, interval: 5 },
466 )
467
468 // The cache data should be removed after the keepUnusedDataFor time,
469 // so wait longer than that
470 await delay(100)
471
472 const stateAfter = storeRef.store.getState()
473
474 expect(api.endpoints.postWithSideEffect.select('1')(stateAfter).data).toBe(
475 undefined,
476 )
477 })
478
479 test('Handles repeated upserts and async lifecycles', async () => {
480 const StateForUpsertFolder = ({ folderId }: { folderId: number }) => {
481 const { status } = api.useGetFolderQuery(folderId)
482
483 return (
484 <>
485 <div>
486 Status getFolder with ID (
487 {folderId === 1 ? 'original request' : 'upserted'}) {folderId}:{' '}
488 <span data-testid={`status-${folderId}`}>{status}</span>
489 </div>
490 </>
491 )
492 }
493
494 const Folder = () => {
495 const { data, isLoading, isError } = api.useGetFolderQuery(1)
496
497 return (
498 <div>
499 <h1>Folders</h1>
500
501 {isLoading && <div>Loading...</div>}
502
503 {isError && <div>Error...</div>}
504
505 <StateForUpsertFolder key={`state-${1}`} folderId={1} />
506 <StateForUpsertFolder key={`state-${2}`} folderId={2} />
507 </div>
508 )
509 }
510
511 render(<Folder />, {
512 wrapper: storeRef.wrapper,
513 })
514
515 await waitFor(() => {
516 const { actions } = storeRef.store.getState()
517 // Inspection:
518 // - 2 inits
519 // - 2 pendings, 2 fulfilleds for the hook queries
520 // - 2 upserts
521 expect(actions.length).toBe(8)
522 expect(
523 actions.filter((a) => api.util.upsertQueryEntries.match(a)).length,
524 ).toBe(2)
525 })
526 expect(screen.getByTestId('status-2').textContent).toBe('fulfilled')
527 })
528 })
529
530 describe('full integration', () => {
531 test('success case', async () => {
532 baseQuery
533 .mockResolvedValueOnce({
534 id: '3',
535 title: 'All about cheese.',
536 contents: 'TODO',
537 })
538 .mockResolvedValueOnce({
539 id: '3',
540 title: 'Meanwhile, this changed server-side.',
541 contents: 'Delicious cheese!',
542 })
543 .mockResolvedValueOnce({
544 id: '3',
545 title: 'Meanwhile, this changed server-side.',
546 contents: 'Delicious cheese!',
547 })
548 .mockResolvedValueOnce(42)
549 const { result } = renderHook(
550 () => ({
551 query: api.endpoints.post.useQuery('3'),
552 mutation: api.endpoints.updatePost.useMutation(),
553 }),
554 {
555 wrapper: storeRef.wrapper,
556 },
557 )
558 await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
559
560 expect(result.current.query.data).toEqual({
561 id: '3',
562 title: 'All about cheese.',
563 contents: 'TODO',
564 })
565
566 await act(async () => {
567 await result.current.mutation[0]({
568 id: '3',
569 contents: 'Delicious cheese!',
570 })
571 })
572
573 expect(result.current.query.data).toEqual({
574 id: '3',
575 title: 'Meanwhile, this changed server-side.',
576 contents: 'Delicious cheese!',
577 })
578
579 await hookWaitFor(() =>
580 expect(result.current.query.data).toEqual({
581 id: '3',
582 title: 'Meanwhile, this changed server-side.',
583 contents: 'Delicious cheese!',
584 }),
585 )
586 })
587
588 test('error case', async () => {
589 baseQuery
590 .mockResolvedValueOnce({
591 id: '3',
592 title: 'All about cheese.',
593 contents: 'TODO',
594 })
595 .mockRejectedValueOnce('some error!')
596 .mockResolvedValueOnce({
597 id: '3',
598 title: 'Meanwhile, this changed server-side.',
599 contents: 'TODO',
600 })
601 .mockResolvedValueOnce(42)
602
603 const { result } = renderHook(
604 () => ({
605 query: api.endpoints.post.useQuery('3'),
606 mutation: api.endpoints.updatePost.useMutation(),
607 }),
608 {
609 wrapper: storeRef.wrapper,
610 },
611 )
612 await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
613
614 expect(result.current.query.data).toEqual({
615 id: '3',
616 title: 'All about cheese.',
617 contents: 'TODO',
618 })
619
620 await act(async () => {
621 await result.current.mutation[0]({
622 id: '3',
623 contents: 'Delicious cheese!',
624 })
625 })
626
627 // optimistic update
628 expect(result.current.query.data).toEqual({
629 id: '3',
630 title: 'All about cheese.',
631 contents: 'Delicious cheese!',
632 })
633
634 // mutation failed - will not invalidate query and not refetch data from the server
635 await expect(() =>
636 hookWaitFor(
637 () =>
638 expect(result.current.query.data).toEqual({
639 id: '3',
640 title: 'Meanwhile, this changed server-side.',
641 contents: 'TODO',
642 }),
643 50,
644 ),
645 ).rejects.toBeTruthy()
646
647 act(() => void result.current.query.refetch())
648
649 // manually refetching gives up-to-date data
650 await hookWaitFor(
651 () =>
652 expect(result.current.query.data).toEqual({
653 id: '3',
654 title: 'Meanwhile, this changed server-side.',
655 contents: 'TODO',
656 }),
657 50,
658 )
659 })
660
661 test('Interop with in-flight requests', async () => {
662 await act(async () => {
663 const fetchRes = storeRef.store.dispatch(
664 api.endpoints.post2.initiate('3'),
665 )
666
667 const upsertRes = storeRef.store.dispatch(
668 api.util.upsertQueryData('post2', '3', {
669 id: '3',
670 title: 'Upserted title',
671 contents: 'Upserted contents',
672 }),
673 )
674
675 const selectEntry = api.endpoints.post2.select('3')
676 await waitFor(
677 () => {
678 const entry1 = selectEntry(storeRef.store.getState())
679 expect(entry1.data).toEqual({
680 id: '3',
681 title: 'Upserted title',
682 contents: 'Upserted contents',
683 })
684 },
685 { interval: 1, timeout: 15 },
686 )
687 await waitFor(
688 () => {
689 const entry2 = selectEntry(storeRef.store.getState())
690 expect(entry2.data).toEqual({
691 id: '3',
692 title: 'All about cheese.',
693 contents: 'TODO',
694 })
695 },
696 { interval: 1 },
697 )
698 })
699 })
700 })