Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test.ts

raw
1 import { server } from '@internal/query/tests/mocks/server'
2 import type { InfiniteQueryActionCreatorResult } from '@reduxjs/toolkit/query/react'
3 import {
4 QueryStatus,
5 createApi,
6 fakeBaseQuery,
7 fetchBaseQuery,
8 } from '@reduxjs/toolkit/query/react'
9 import { HttpResponse, delay, http } from 'msw'
10 import { actionsReducer, setupApiStore } from '../../tests/utils/helpers'
11 import type { InfiniteQueryResultFlags } from '../core/buildSelectors'
12
13 describe('Infinite queries', () => {
14 type Pokemon = {
15 id: string
16 name: string
17 }
18
19 let counters: Record<string, number> = {}
20 let queryCounter = 0
21
22 const pokemonApi = createApi({
23 baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
24 endpoints: (build) => ({
25 getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
26 infiniteQueryOptions: {
27 initialPageParam: 0,
28 getNextPageParam: (
29 lastPage,
30 allPages,
31 lastPageParam,
32 allPageParams,
33 ) => lastPageParam + 1,
34 getPreviousPageParam: (
35 firstPage,
36 allPages,
37 firstPageParam,
38 allPageParams,
39 ) => {
40 return firstPageParam > 0 ? firstPageParam - 1 : undefined
41 },
42 },
43 query({ pageParam }) {
44 return `https://example.com/listItems?page=${pageParam}`
45 },
46 }),
47 getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>(
48 {
49 infiniteQueryOptions: {
50 initialPageParam: 0,
51 maxPages: 3,
52 getNextPageParam: (
53 lastPage,
54 allPages,
55 lastPageParam,
56 allPageParams,
57 ) => lastPageParam + 1,
58 getPreviousPageParam: (
59 firstPage,
60 allPages,
61 firstPageParam,
62 allPageParams,
63 ) => {
64 return firstPageParam > 0 ? firstPageParam - 1 : undefined
65 },
66 },
67 query({ pageParam }) {
68 return `https://example.com/listItems?page=${pageParam}`
69 },
70 },
71 ),
72 counters: build.query<{ id: string; counter: number }, string>({
73 queryFn: async (arg) => {
74 if (!(arg in counters)) {
75 counters[arg] = 0
76 }
77 counters[arg]++
78
79 return { data: { id: arg, counter: counters[arg] } }
80 },
81 }),
82 }),
83 })
84
85 let hitCounter = 0
86
87 type HitCounter = { page: number; hitCounter: number }
88
89 const countersApi = createApi({
90 baseQuery: fakeBaseQuery(),
91 tagTypes: ['Counter'],
92 endpoints: (build) => ({
93 counters: build.infiniteQuery<HitCounter, string, number>({
94 queryFn({ pageParam }) {
95 hitCounter++
96
97 return { data: { page: pageParam, hitCounter } }
98 },
99 infiniteQueryOptions: {
100 initialPageParam: 0,
101 getNextPageParam: (
102 lastPage,
103 allPages,
104 lastPageParam,
105 allPageParams,
106 ) => lastPageParam + 1,
107 },
108 providesTags: ['Counter'],
109 }),
110 mutation: build.mutation<null, void>({
111 queryFn: async () => {
112 return { data: null }
113 },
114 invalidatesTags: ['Counter'],
115 }),
116 }),
117 })
118
119 let storeRef = setupApiStore(
120 pokemonApi,
121 { ...actionsReducer },
122 {
123 withoutTestLifecycles: true,
124 },
125 )
126
127 beforeEach(() => {
128 server.use(
129 http.get('https://example.com/listItems', ({ request }) => {
130 const url = new URL(request.url)
131 const pageString = url.searchParams.get('page')
132 const pageNum = parseInt(pageString || '0')
133 queryCounter++
134
135 const results: Pokemon[] = [
136 { id: `${pageNum}`, name: `Pokemon ${pageNum}` },
137 ]
138 return HttpResponse.json(results)
139 }),
140 )
141
142 storeRef = setupApiStore(
143 pokemonApi,
144 { ...actionsReducer },
145 {
146 withoutTestLifecycles: true,
147 },
148 )
149
150 counters = {}
151
152 hitCounter = 0
153 queryCounter = 0
154 })
155
156 type InfiniteQueryResult = Awaited<InfiniteQueryActionCreatorResult<any>>
157
158 const checkResultData = (
159 result: InfiniteQueryResult,
160 expectedValues: Pokemon[][],
161 ) => {
162 expect(result.status).toBe(QueryStatus.fulfilled)
163 if (result.status === QueryStatus.fulfilled) {
164 expect(result.data.pages).toEqual(expectedValues)
165 }
166 }
167
168 const checkResultLength = (
169 result: InfiniteQueryResult,
170 expectedLength: number,
171 ) => {
172 expect(result.status).toBe(QueryStatus.fulfilled)
173 if (result.status === QueryStatus.fulfilled) {
174 expect(result.data.pages).toHaveLength(expectedLength)
175 }
176 }
177
178 test('Basic infinite query behavior', async () => {
179 const checkFlags = (
180 value: unknown,
181 expectedFlags: Partial<InfiniteQueryResultFlags>,
182 ) => {
183 const actualFlags: InfiniteQueryResultFlags = {
184 hasNextPage: false,
185 hasPreviousPage: false,
186 isFetchingNextPage: false,
187 isFetchingPreviousPage: false,
188 isFetchNextPageError: false,
189 isFetchPreviousPageError: false,
190 ...expectedFlags,
191 }
192
193 expect(value).toMatchObject(actualFlags)
194 }
195
196 const checkEntryFlags = (
197 arg: string,
198 expectedFlags: Partial<InfiniteQueryResultFlags>,
199 ) => {
200 const selector = pokemonApi.endpoints.getInfinitePokemon.select(arg)
201 const entry = selector(storeRef.store.getState())
202
203 checkFlags(entry, expectedFlags)
204 }
205
206 const res1 = storeRef.store.dispatch(
207 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
208 )
209
210 checkEntryFlags('fire', {})
211
212 const entry1InitialLoad = await res1
213
214 checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
215 checkFlags(entry1InitialLoad, {
216 hasNextPage: true,
217 })
218
219 const res2 = storeRef.store.dispatch(
220 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
221 direction: 'forward',
222 }),
223 )
224
225 checkEntryFlags('fire', {
226 hasNextPage: true,
227 isFetchingNextPage: true,
228 })
229
230 const entry1SecondPage = await res2
231
232 checkResultData(entry1SecondPage, [
233 [{ id: '0', name: 'Pokemon 0' }],
234 [{ id: '1', name: 'Pokemon 1' }],
235 ])
236 checkFlags(entry1SecondPage, {
237 hasNextPage: true,
238 })
239
240 const res3 = storeRef.store.dispatch(
241 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
242 direction: 'backward',
243 }),
244 )
245
246 checkEntryFlags('fire', {
247 hasNextPage: true,
248 isFetchingPreviousPage: true,
249 })
250
251 const entry1PrevPageMissing = await res3
252
253 checkResultData(entry1PrevPageMissing, [
254 [{ id: '0', name: 'Pokemon 0' }],
255 [{ id: '1', name: 'Pokemon 1' }],
256 ])
257 checkFlags(entry1PrevPageMissing, {
258 hasNextPage: true,
259 })
260
261 const res4 = storeRef.store.dispatch(
262 pokemonApi.endpoints.getInfinitePokemon.initiate('water', {
263 initialPageParam: 3,
264 }),
265 )
266
267 checkEntryFlags('water', {})
268
269 const entry2InitialLoad = await res4
270
271 checkResultData(entry2InitialLoad, [[{ id: '3', name: 'Pokemon 3' }]])
272 checkFlags(entry2InitialLoad, {
273 hasNextPage: true,
274 hasPreviousPage: true,
275 })
276
277 const res5 = storeRef.store.dispatch(
278 pokemonApi.endpoints.getInfinitePokemon.initiate('water', {
279 direction: 'forward',
280 }),
281 )
282
283 checkEntryFlags('water', {
284 hasNextPage: true,
285 hasPreviousPage: true,
286 isFetchingNextPage: true,
287 })
288
289 const entry2NextPage = await res5
290
291 checkResultData(entry2NextPage, [
292 [{ id: '3', name: 'Pokemon 3' }],
293 [{ id: '4', name: 'Pokemon 4' }],
294 ])
295 checkFlags(entry2NextPage, {
296 hasNextPage: true,
297 hasPreviousPage: true,
298 })
299
300 const res6 = storeRef.store.dispatch(
301 pokemonApi.endpoints.getInfinitePokemon.initiate('water', {
302 direction: 'backward',
303 }),
304 )
305
306 checkEntryFlags('water', {
307 hasNextPage: true,
308 hasPreviousPage: true,
309 isFetchingPreviousPage: true,
310 })
311
312 const entry2PrevPage = await res6
313
314 checkResultData(entry2PrevPage, [
315 [{ id: '2', name: 'Pokemon 2' }],
316 [{ id: '3', name: 'Pokemon 3' }],
317 [{ id: '4', name: 'Pokemon 4' }],
318 ])
319 checkFlags(entry2PrevPage, {
320 hasNextPage: true,
321 hasPreviousPage: true,
322 })
323 })
324
325 test('does not have a page limit without maxPages', async () => {
326 for (let i = 1; i <= 10; i++) {
327 const res = await storeRef.store.dispatch(
328 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
329 direction: 'forward',
330 }),
331 )
332
333 checkResultLength(res, i)
334 }
335 })
336
337 test('applies a page limit with maxPages', async () => {
338 for (let i = 1; i <= 10; i++) {
339 const res = await storeRef.store.dispatch(
340 pokemonApi.endpoints.getInfinitePokemonWithMax.initiate('fire', {
341 direction: 'forward',
342 }),
343 )
344
345 checkResultLength(res, Math.min(i, 3))
346 }
347
348 // Should now have entries 7, 8, 9 after the loop
349
350 const res = await storeRef.store.dispatch(
351 pokemonApi.endpoints.getInfinitePokemonWithMax.initiate('fire', {
352 direction: 'backward',
353 }),
354 )
355
356 checkResultData(res, [
357 [{ id: '6', name: 'Pokemon 6' }],
358 [{ id: '7', name: 'Pokemon 7' }],
359 [{ id: '8', name: 'Pokemon 8' }],
360 ])
361 })
362
363 test('validates maxPages during createApi call', async () => {
364 vi.stubEnv('NODE_ENV', 'development')
365
366 const createApiWithMaxPages = (
367 maxPages: number,
368 getPreviousPageParam: (() => number) | undefined,
369 ) => {
370 createApi({
371 baseQuery: fakeBaseQuery(),
372 endpoints: (build) => ({
373 getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
374 query(pageParam) {
375 return `https://example.com/listItems?page=${pageParam}`
376 },
377 infiniteQueryOptions: {
378 initialPageParam: 0,
379 maxPages,
380 getNextPageParam: () => 1,
381 getPreviousPageParam,
382 },
383 }),
384 }),
385 })
386 }
387
388 expect(() => createApiWithMaxPages(0, () => 0)).toThrowError(
389 `maxPages for endpoint 'getInfinitePokemon' must be a number greater than 0`,
390 )
391
392 expect(() => createApiWithMaxPages(1, undefined)).toThrowError(
393 `getPreviousPageParam for endpoint 'getInfinitePokemon' must be a function if maxPages is used`,
394 )
395 })
396
397 test('refetches all existing pages', async () => {
398 const checkResultData = (
399 result: InfiniteQueryResult,
400 expectedValues: HitCounter[],
401 ) => {
402 expect(result.status).toBe(QueryStatus.fulfilled)
403 if (result.status === QueryStatus.fulfilled) {
404 expect(result.data.pages).toEqual(expectedValues)
405 }
406 }
407
408 const storeRef = setupApiStore(
409 countersApi,
410 { ...actionsReducer },
411 {
412 withoutTestLifecycles: true,
413 },
414 )
415
416 await storeRef.store.dispatch(
417 countersApi.endpoints.counters.initiate('item', {
418 initialPageParam: 3,
419 }),
420 )
421
422 await storeRef.store.dispatch(
423 countersApi.endpoints.counters.initiate('item', {
424 direction: 'forward',
425 }),
426 )
427
428 const thirdPromise = storeRef.store.dispatch(
429 countersApi.endpoints.counters.initiate('item', {
430 direction: 'forward',
431 }),
432 )
433
434 const thirdRes = await thirdPromise
435
436 checkResultData(thirdRes, [
437 { page: 3, hitCounter: 1 },
438 { page: 4, hitCounter: 2 },
439 { page: 5, hitCounter: 3 },
440 ])
441
442 const fourthRes = await thirdPromise.refetch()
443
444 checkResultData(fourthRes, [
445 { page: 3, hitCounter: 4 },
446 { page: 4, hitCounter: 5 },
447 { page: 5, hitCounter: 6 },
448 ])
449 })
450
451 test('Refetches on invalidation', async () => {
452 const checkResultData = (
453 result: InfiniteQueryResult,
454 expectedValues: HitCounter[],
455 ) => {
456 expect(result.status).toBe(QueryStatus.fulfilled)
457 if (result.status === QueryStatus.fulfilled) {
458 expect(result.data.pages).toEqual(expectedValues)
459 }
460 }
461
462 const storeRef = setupApiStore(
463 countersApi,
464 { ...actionsReducer },
465 {
466 withoutTestLifecycles: true,
467 },
468 )
469
470 await storeRef.store.dispatch(
471 countersApi.endpoints.counters.initiate('item', {
472 initialPageParam: 3,
473 }),
474 )
475
476 await storeRef.store.dispatch(
477 countersApi.endpoints.counters.initiate('item', {
478 direction: 'forward',
479 }),
480 )
481
482 const thirdPromise = storeRef.store.dispatch(
483 countersApi.endpoints.counters.initiate('item', {
484 direction: 'forward',
485 }),
486 )
487
488 const thirdRes = await thirdPromise
489
490 checkResultData(thirdRes, [
491 { page: 3, hitCounter: 1 },
492 { page: 4, hitCounter: 2 },
493 { page: 5, hitCounter: 3 },
494 ])
495
496 await storeRef.store.dispatch(countersApi.endpoints.mutation.initiate())
497
498 let entry = countersApi.endpoints.counters.select('item')(
499 storeRef.store.getState(),
500 )
501 const promise = storeRef.store.dispatch(
502 countersApi.util.getRunningQueryThunk('counters', 'item'),
503 )
504 const promises = storeRef.store.dispatch(
505 countersApi.util.getRunningQueriesThunk(),
506 )
507 expect(entry).toMatchObject({
508 status: 'pending',
509 })
510
511 expect(promise).toBeInstanceOf(Promise)
512
513 expect(promises).toEqual([promise])
514
515 const finalRes = await promise
516
517 checkResultData(finalRes as any, [
518 { page: 3, hitCounter: 4 },
519 { page: 4, hitCounter: 5 },
520 { page: 5, hitCounter: 6 },
521 ])
522 })
523
524 test('Refetches on polling', async () => {
525 const checkResultData = (
526 result: InfiniteQueryResult,
527 expectedValues: HitCounter[],
528 ) => {
529 expect(result.status).toBe(QueryStatus.fulfilled)
530 if (result.status === QueryStatus.fulfilled) {
531 expect(result.data.pages).toEqual(expectedValues)
532 }
533 }
534
535 const storeRef = setupApiStore(
536 countersApi,
537 { ...actionsReducer },
538 {
539 withoutTestLifecycles: true,
540 },
541 )
542
543 await storeRef.store.dispatch(
544 countersApi.endpoints.counters.initiate('item', {
545 initialPageParam: 3,
546 }),
547 )
548
549 await storeRef.store.dispatch(
550 countersApi.endpoints.counters.initiate('item', {
551 direction: 'forward',
552 }),
553 )
554
555 const thirdPromise = storeRef.store.dispatch(
556 countersApi.endpoints.counters.initiate('item', {
557 direction: 'forward',
558 }),
559 )
560
561 const thirdRes = await thirdPromise
562
563 checkResultData(thirdRes, [
564 { page: 3, hitCounter: 1 },
565 { page: 4, hitCounter: 2 },
566 { page: 5, hitCounter: 3 },
567 ])
568
569 thirdPromise.updateSubscriptionOptions({
570 pollingInterval: 50,
571 })
572
573 await delay(25)
574
575 let entry = countersApi.endpoints.counters.select('item')(
576 storeRef.store.getState(),
577 )
578
579 checkResultData(thirdRes, [
580 { page: 3, hitCounter: 1 },
581 { page: 4, hitCounter: 2 },
582 { page: 5, hitCounter: 3 },
583 ])
584
585 await delay(50)
586
587 entry = countersApi.endpoints.counters.select('item')(
588 storeRef.store.getState(),
589 )
590
591 checkResultData(entry as any, [
592 { page: 3, hitCounter: 4 },
593 { page: 4, hitCounter: 5 },
594 { page: 5, hitCounter: 6 },
595 ])
596 })
597
598 test('Handles multiple next page fetches at once', async () => {
599 const initialEntry = await storeRef.store.dispatch(
600 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
601 )
602
603 checkResultData(initialEntry, [[{ id: '0', name: 'Pokemon 0' }]])
604
605 expect(queryCounter).toBe(1)
606
607 const promise1 = storeRef.store.dispatch(
608 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
609 direction: 'forward',
610 }),
611 )
612
613 expect(queryCounter).toBe(1)
614
615 const promise2 = storeRef.store.dispatch(
616 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
617 direction: 'forward',
618 }),
619 )
620
621 const entry1 = await promise1
622 const entry2 = await promise2
623
624 // The second thunk should have bailed out because the entry was now
625 // pending, so we should only have sent one request.
626 expect(queryCounter).toBe(2)
627
628 expect(entry1).toEqual(entry2)
629
630 checkResultData(entry1, [
631 [{ id: '0', name: 'Pokemon 0' }],
632 [{ id: '1', name: 'Pokemon 1' }],
633 ])
634
635 expect(queryCounter).toBe(2)
636
637 const promise3 = storeRef.store.dispatch(
638 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
639 direction: 'forward',
640 }),
641 )
642
643 expect(queryCounter).toBe(2)
644
645 // We can abort an existing promise, but due to timing issues,
646 // we have to await the promise first before triggering the next request.
647 promise3.abort()
648 const entry3 = await promise3
649
650 const promise4 = storeRef.store.dispatch(
651 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
652 direction: 'forward',
653 }),
654 )
655
656 const entry4 = await promise4
657
658 expect(queryCounter).toBe(4)
659
660 checkResultData(entry4, [
661 [{ id: '0', name: 'Pokemon 0' }],
662 [{ id: '1', name: 'Pokemon 1' }],
663 [{ id: '2', name: 'Pokemon 2' }],
664 ])
665 })
666
667 test('can fetch pages with refetchOnMountOrArgChange active', async () => {
668 const pokemonApiWithRefetch = createApi({
669 baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
670 endpoints: (build) => ({
671 getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
672 infiniteQueryOptions: {
673 initialPageParam: 0,
674 getNextPageParam: (
675 lastPage,
676 allPages,
677 // Page param type should be `number`
678 lastPageParam,
679 allPageParams,
680 ) => lastPageParam + 1,
681 getPreviousPageParam: (
682 firstPage,
683 allPages,
684 firstPageParam,
685 allPageParams,
686 ) => {
687 return firstPageParam > 0 ? firstPageParam - 1 : undefined
688 },
689 },
690 query({ pageParam }) {
691 return `https://example.com/listItems?page=${pageParam}`
692 },
693 }),
694 }),
695 refetchOnMountOrArgChange: true,
696 })
697
698 const storeRef = setupApiStore(
699 pokemonApiWithRefetch,
700 { ...actionsReducer },
701 {
702 withoutTestLifecycles: true,
703 },
704 )
705
706 const res1 = storeRef.store.dispatch(
707 pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {}),
708 )
709
710 const entry1InitialLoad = await res1
711 checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
712
713 const res2 = storeRef.store.dispatch(
714 pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {
715 direction: 'forward',
716 }),
717 )
718
719 const entry1SecondPage = await res2
720 checkResultData(entry1SecondPage, [
721 [{ id: '0', name: 'Pokemon 0' }],
722 [{ id: '1', name: 'Pokemon 1' }],
723 ])
724
725 expect(queryCounter).toBe(2)
726
727 const entry2InitialLoad = await storeRef.store.dispatch(
728 pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('water', {}),
729 )
730
731 checkResultData(entry2InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
732
733 expect(queryCounter).toBe(3)
734
735 const entry2SecondPage = await storeRef.store.dispatch(
736 pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('water', {
737 direction: 'forward',
738 }),
739 )
740 checkResultData(entry2SecondPage, [
741 [{ id: '0', name: 'Pokemon 0' }],
742 [{ id: '1', name: 'Pokemon 1' }],
743 ])
744
745 expect(queryCounter).toBe(4)
746
747 // Should now be able to switch back to the first query.
748 // The hooks dispatch on arg change without a direction.
749 // That should trigger a refetch of the first query, meaning two requests.
750 // It should also _replace_ the existing results, rather than appending
751 // duplicate entries ([0, 1, 0, 1])
752 const entry1Refetched = await storeRef.store.dispatch(
753 pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {}),
754 )
755
756 checkResultData(entry1Refetched, [
757 [{ id: '0', name: 'Pokemon 0' }],
758 [{ id: '1', name: 'Pokemon 1' }],
759 ])
760
761 expect(queryCounter).toBe(6)
762 })
763
764 test('Works with cache manipulation utils', async () => {
765 const res1 = storeRef.store.dispatch(
766 pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
767 )
768
769 const entry1InitialLoad = await res1
770 checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
771
772 storeRef.store.dispatch(
773 pokemonApi.util.updateQueryData('getInfinitePokemon', 'fire', (draft) => {
774 draft.pages.push([{ id: '1', name: 'Pokemon 1' }])
775 draft.pageParams.push(1)
776 }),
777 )
778
779 const selectFire = pokemonApi.endpoints.getInfinitePokemon.select('fire')
780 const entry1Updated = selectFire(storeRef.store.getState())
781
782 expect(entry1Updated.data).toEqual({
783 pages: [
784 [{ id: '0', name: 'Pokemon 0' }],
785 [{ id: '1', name: 'Pokemon 1' }],
786 ],
787 pageParams: [0, 1],
788 })
789
790 const res2 = storeRef.store.dispatch(
791 pokemonApi.util.upsertQueryData('getInfinitePokemon', 'water', {
792 pages: [[{ id: '2', name: 'Pokemon 2' }]],
793 pageParams: [2],
794 }),
795 )
796
797 const entry2InitialLoad = await res2
798 const selectWater = pokemonApi.endpoints.getInfinitePokemon.select('water')
799 const entry2Updated = selectWater(storeRef.store.getState())
800
801 expect(entry2Updated.data).toEqual({
802 pages: [[{ id: '2', name: 'Pokemon 2' }]],
803 pageParams: [2],
804 })
805
806 storeRef.store.dispatch(
807 pokemonApi.util.upsertQueryEntries([
808 {
809 endpointName: 'getInfinitePokemon',
810 arg: 'air',
811 value: {
812 pages: [[{ id: '3', name: 'Pokemon 3' }]],
813 pageParams: [3],
814 },
815 },
816 ]),
817 )
818
819 const selectAir = pokemonApi.endpoints.getInfinitePokemon.select('air')
820 const entry3Initial = selectAir(storeRef.store.getState())
821
822 expect(entry3Initial.data).toEqual({
823 pages: [[{ id: '3', name: 'Pokemon 3' }]],
824 pageParams: [3],
825 })
826
827 await storeRef.store.dispatch(
828 pokemonApi.endpoints.getInfinitePokemon.initiate('air', {
829 direction: 'forward',
830 }),
831 )
832
833 const entry3Updated = selectAir(storeRef.store.getState())
834
835 expect(entry3Updated.data).toEqual({
836 pages: [
837 [{ id: '3', name: 'Pokemon 3' }],
838 [{ id: '4', name: 'Pokemon 4' }],
839 ],
840 pageParams: [3, 4],
841 })
842 })
843
844 test('Cache lifecycle methods are called', async () => {
845 const cacheEntryAddedCallback = vi.fn()
846 const queryStartedCallback = vi.fn()
847
848 const pokemonApi = createApi({
849 baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
850 endpoints: (build) => ({
851 getInfinitePokemonWithLifecycles: build.infiniteQuery<
852 Pokemon[],
853 string,
854 number
855 >({
856 infiniteQueryOptions: {
857 initialPageParam: 0,
858 getNextPageParam: (
859 lastPage,
860 allPages,
861 // Page param type should be `number`
862 lastPageParam,
863 allPageParams,
864 ) => lastPageParam + 1,
865 getPreviousPageParam: (
866 firstPage,
867 allPages,
868 firstPageParam,
869 allPageParams,
870 ) => {
871 return firstPageParam > 0 ? firstPageParam - 1 : undefined
872 },
873 },
874 query({ pageParam }) {
875 return `https://example.com/listItems?page=${pageParam}`
876 },
877 async onCacheEntryAdded(arg, api) {
878 const data = await api.cacheDataLoaded
879 cacheEntryAddedCallback(arg, data)
880 },
881 async onQueryStarted(arg, api) {
882 const data = await api.queryFulfilled
883 queryStartedCallback(arg, data)
884 },
885 }),
886 }),
887 })
888
889 const storeRef = setupApiStore(
890 pokemonApi,
891 { ...actionsReducer },
892 {
893 withoutTestLifecycles: true,
894 },
895 )
896
897 const res1 = storeRef.store.dispatch(
898 pokemonApi.endpoints.getInfinitePokemonWithLifecycles.initiate(
899 'fire',
900 {},
901 ),
902 )
903
904 const entry1InitialLoad = await res1
905 checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
906
907 expect(cacheEntryAddedCallback).toHaveBeenCalledWith('fire', {
908 data: {
909 pages: [[{ id: '0', name: 'Pokemon 0' }]],
910 pageParams: [0],
911 },
912 meta: undefined,
913 })
914
915 expect(queryStartedCallback).toHaveBeenCalledWith('fire', {
916 data: {
917 pages: [[{ id: '0', name: 'Pokemon 0' }]],
918 pageParams: [0],
919 },
920 meta: undefined,
921 })
922 })
923
924 test('Can use transformResponse', async () => {
925 type PokemonPage = { items: Pokemon[]; page: number }
926 const pokemonApi = createApi({
927 baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
928 endpoints: (build) => ({
929 getInfinitePokemonWithTransform: build.infiniteQuery<
930 PokemonPage,
931 string,
932 number
933 >({
934 infiniteQueryOptions: {
935 initialPageParam: 0,
936 getNextPageParam: (
937 lastPage,
938 allPages,
939 // Page param type should be `number`
940 lastPageParam,
941 allPageParams,
942 ) => lastPageParam + 1,
943 },
944 query({ pageParam }) {
945 return `https://example.com/listItems?page=${pageParam}`
946 },
947 transformResponse(baseQueryReturnValue: Pokemon[], meta, arg) {
948 expect(Array.isArray(baseQueryReturnValue)).toBe(true)
949 return {
950 items: baseQueryReturnValue,
951 page: arg.pageParam,
952 }
953 },
954 }),
955 }),
956 })
957
958 const storeRef = setupApiStore(
959 pokemonApi,
960 { ...actionsReducer },
961 {
962 withoutTestLifecycles: true,
963 },
964 )
965
966 const checkResultData = (
967 result: InfiniteQueryResult,
968 expectedValues: PokemonPage[],
969 ) => {
970 expect(result.status).toBe(QueryStatus.fulfilled)
971 if (result.status === QueryStatus.fulfilled) {
972 expect(result.data.pages).toEqual(expectedValues)
973 }
974 }
975
976 const res1 = storeRef.store.dispatch(
977 pokemonApi.endpoints.getInfinitePokemonWithTransform.initiate('fire', {}),
978 )
979
980 const entry1InitialLoad = await res1
981 checkResultData(entry1InitialLoad, [
982 { items: [{ id: '0', name: 'Pokemon 0' }], page: 0 },
983 ])
984
985 const entry1Updated = await storeRef.store.dispatch(
986 pokemonApi.endpoints.getInfinitePokemonWithTransform.initiate('fire', {
987 direction: 'forward',
988 }),
989 )
990
991 checkResultData(entry1Updated, [
992 { items: [{ id: '0', name: 'Pokemon 0' }], page: 0 },
993 { items: [{ id: '1', name: 'Pokemon 1' }], page: 1 },
994 ])
995 })
996 })