|
| 1 | +import { |
| 2 | + createApi, |
| 3 | + fetchBaseQuery, |
| 4 | + QueryStatus, |
| 5 | +} from '@reduxjs/toolkit/query/react' |
| 6 | +import { setupApiStore } from '../../tests/utils/helpers' |
| 7 | + |
| 8 | +describe('Infinite queries', () => { |
| 9 | + test('Basic infinite query behavior', async () => { |
| 10 | + type Pokemon = { |
| 11 | + id: string |
| 12 | + name: string |
| 13 | + } |
| 14 | + |
| 15 | + const pokemonApi = createApi({ |
| 16 | + baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }), |
| 17 | + endpoints: (builder) => ({ |
| 18 | + getInfinitePokemon: builder.infiniteQuery<Pokemon[], string, number>({ |
| 19 | + infiniteQueryOptions: { |
| 20 | + initialPageParam: 0, |
| 21 | + getNextPageParam: ( |
| 22 | + lastPage, |
| 23 | + allPages, |
| 24 | + lastPageParam, |
| 25 | + allPageParams, |
| 26 | + ) => { |
| 27 | + expectTypeOf(lastPage).toEqualTypeOf<Pokemon[]>() |
| 28 | + |
| 29 | + expectTypeOf(allPages).toEqualTypeOf<Pokemon[][]>() |
| 30 | + |
| 31 | + expectTypeOf(lastPageParam).toBeNumber() |
| 32 | + |
| 33 | + expectTypeOf(allPageParams).toEqualTypeOf<number[]>() |
| 34 | + |
| 35 | + return lastPageParam + 1 |
| 36 | + }, |
| 37 | + }, |
| 38 | + query(pageParam) { |
| 39 | + expectTypeOf(pageParam).toBeNumber() |
| 40 | + |
| 41 | + return `https://example.com/listItems?page=${pageParam}` |
| 42 | + }, |
| 43 | + }), |
| 44 | + }), |
| 45 | + }) |
| 46 | + |
| 47 | + const storeRef = setupApiStore(pokemonApi, undefined, { |
| 48 | + withoutTestLifecycles: true, |
| 49 | + }) |
| 50 | + |
| 51 | + expectTypeOf(pokemonApi.endpoints.getInfinitePokemon.initiate) |
| 52 | + .parameter(0) |
| 53 | + .toBeString() |
| 54 | + |
| 55 | + const res = storeRef.store.dispatch( |
| 56 | + pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}), |
| 57 | + ) |
| 58 | + |
| 59 | + const firstResult = await res |
| 60 | + |
| 61 | + if (firstResult.status === QueryStatus.fulfilled) { |
| 62 | + expectTypeOf(firstResult.data.pages).toEqualTypeOf<Pokemon[][]>() |
| 63 | + expectTypeOf(firstResult.data.pageParams).toEqualTypeOf<number[]>() |
| 64 | + } |
| 65 | + |
| 66 | + storeRef.store.dispatch( |
| 67 | + pokemonApi.endpoints.getInfinitePokemon.initiate('fire', { |
| 68 | + direction: 'forward', |
| 69 | + }), |
| 70 | + ) |
| 71 | + }) |
| 72 | +}) |
0 commit comments