From 00f9261ad7b4b0d39294dfcba459c764c48cf39f Mon Sep 17 00:00:00 2001 From: Sebastien Guillemot Date: Thu, 2 Feb 2023 05:52:27 +0900 Subject: [PATCH] Write test to expose bug on cache invalidation of queries that use serializeQueryArgs --- .../toolkit/src/query/tests/createApi.test.ts | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/packages/toolkit/src/query/tests/createApi.test.ts b/packages/toolkit/src/query/tests/createApi.test.ts index 4cc4eae66f..c7cf1f61b9 100644 --- a/packages/toolkit/src/query/tests/createApi.test.ts +++ b/packages/toolkit/src/query/tests/createApi.test.ts @@ -876,8 +876,13 @@ describe('custom serializeQueryArgs per endpoint', () => { }, } + const TagTypes = { + ListItemsTag: 'ListItemsTag', + } as const; + const api = createApi({ baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }), + tagTypes: Object.values(TagTypes), serializeQueryArgs: ({ endpointName, queryArgs }) => `base-${endpointName}-${queryArgs}`, endpoints: (build) => ({ @@ -944,6 +949,16 @@ describe('custom serializeQueryArgs per endpoint', () => { return currentArg !== previousArg }, }), + listItems3: build.query({ + query: (pageNumber) => { + console.log(pageNumber); + return `/listItems3?page=${pageNumber}` + }, + serializeQueryArgs: ({ endpointName }) => { + return endpointName + }, + providesTags: [TagTypes.ListItemsTag], + }), }), }) @@ -1083,4 +1098,35 @@ describe('custom serializeQueryArgs per endpoint', () => { baseQueryMeta: expect.any(Object), }) }) + + test('serializeQueryArgs allows refetching as args change with same cache key if invalidated', async () => { + const allItems = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i'] + const PAGE_SIZE = 3 + + server.use( + rest.get('https://example.com/listItems3', (req, res, ctx) => { + const pageString = req.url.searchParams.get('page') + const pageNum = parseInt(pageString || '0') + + const results = paginate(allItems, PAGE_SIZE, pageNum) + return res(ctx.json(results)) + }) + ) + + // Page number shouldn't matter here, because the cache key ignores that. + // We just need to select the only cache entry. + const selectListItems = api.endpoints.listItems3.select(0) + + await storeRef.store.dispatch(api.endpoints.listItems3.initiate(1)) + + const initialEntry = selectListItems(storeRef.store.getState()) + expect(initialEntry.data).toEqual(['a', 'b', 'c']) + + await storeRef.store.dispatch(api.util.invalidateTags([TagTypes.ListItemsTag])); + + // TODO: due to bug, the call to listItems3 still uses `1` instead of `2` as expected + await storeRef.store.dispatch(api.endpoints.listItems3.initiate(2)) + const updatedEntry = selectListItems(storeRef.store.getState()) + expect(updatedEntry.data).toEqual(['a', 'b', 'c', 'd', 'e', 'f']) + }) })