Skip to content

Commit cd17d41

Browse files
authored
test: add invalidate query tests (#1052)
1 parent 4d1bd35 commit cd17d41

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/core/tests/queryCache.test.tsx

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,28 @@ describe('queryCache', () => {
314314
expect(queryFn2).toHaveBeenCalledTimes(2)
315315
})
316316

317+
test('invalidateQueries should not refetch inactive queries by default', async () => {
318+
const key1 = queryKey()
319+
const key2 = queryKey()
320+
const queryFn1 = jest.fn()
321+
const queryFn2 = jest.fn()
322+
const cache = new QueryCache()
323+
await cache.fetchQuery(key1, queryFn1)
324+
await cache.fetchQuery(key2, queryFn2)
325+
const query1 = cache.getQuery(key1)!
326+
const observer = new QueryObserver({
327+
...query1.config,
328+
enabled: false,
329+
staleTime: Infinity,
330+
})
331+
observer.subscribe()
332+
await cache.invalidateQueries(key1)
333+
observer.unsubscribe()
334+
cache.clear()
335+
expect(queryFn1).toHaveBeenCalledTimes(1)
336+
expect(queryFn2).toHaveBeenCalledTimes(1)
337+
})
338+
317339
test('getQueries should return queries that partially match queryKey', async () => {
318340
const key1 = queryKey()
319341
const key2 = queryKey()

src/react/tests/useQuery.test.tsx

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,46 @@ describe('useQuery', () => {
584584
})
585585
})
586586

587+
it('should not refetch disabled query when invalidated with invalidateQueries', async () => {
588+
const key = queryKey()
589+
const states: QueryResult<number>[] = []
590+
let count = 0
591+
592+
function Page() {
593+
const state = useQuery(
594+
key,
595+
async () => {
596+
await sleep(10)
597+
count++
598+
return count
599+
},
600+
{ enabled: false }
601+
)
602+
603+
states.push(state)
604+
605+
React.useEffect(() => {
606+
setTimeout(() => {
607+
queryCache.invalidateQueries(key)
608+
}, 20)
609+
}, [])
610+
611+
return null
612+
}
613+
614+
render(<Page />)
615+
616+
await waitForMs(100)
617+
618+
expect(states.length).toBe(1)
619+
expect(states[0]).toMatchObject({
620+
data: undefined,
621+
isFetching: false,
622+
isSuccess: false,
623+
isStale: true,
624+
})
625+
})
626+
587627
it('should keep the previous data when keepPreviousData is set', async () => {
588628
const key = queryKey()
589629
const states: QueryResult<number>[] = []

0 commit comments

Comments
 (0)