1- import { afterEach , beforeEach , describe , expect , it } from 'vitest'
2- import { render , waitFor } from '@testing-library/react'
1+ import { afterEach , beforeEach , describe , expect , it , vi } from 'vitest'
2+ import { act , render } from '@testing-library/react'
33import * as React from 'react'
44import { QueryClient , useQueries } from '@tanstack/react-query'
5+ import { sleep } from '@tanstack/query-test-utils'
56import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
67import type {
78 PersistedClient ,
@@ -13,6 +14,7 @@ describe('useQueries with persist and memoized combine', () => {
1314 const storage : { [ key : string ] : string } = { }
1415
1516 beforeEach ( ( ) => {
17+ vi . useFakeTimers ( )
1618 Object . defineProperty ( window , 'localStorage' , {
1719 value : {
1820 getItem : ( key : string ) => storage [ key ] || null ,
@@ -31,6 +33,7 @@ describe('useQueries with persist and memoized combine', () => {
3133 } )
3234
3335 afterEach ( ( ) => {
36+ vi . useRealTimers ( )
3437 Object . keys ( storage ) . forEach ( ( key ) => delete storage [ key ] )
3538 } )
3639
@@ -51,10 +54,9 @@ describe('useQueries with persist and memoized combine', () => {
5154 } ,
5255 restoreClient : async ( ) => {
5356 const stored = storage [ 'REACT_QUERY_OFFLINE_CACHE' ]
54- if ( stored ) {
55- await new Promise ( ( resolve ) => setTimeout ( resolve , 10 ) )
56- return JSON . parse ( stored ) as PersistedClient
57- }
57+ if ( stored )
58+ return sleep ( 10 ) . then ( ( ) => JSON . parse ( stored ) as PersistedClient )
59+
5860 return undefined
5961 } ,
6062 removeClient : ( ) => {
@@ -95,7 +97,7 @@ describe('useQueries with persist and memoized combine', () => {
9597 const combinedQueries = useQueries ( {
9698 queries : [ 1 , 2 , 3 ] . map ( ( id ) => ( {
9799 queryKey : [ 'post' , id ] ,
98- queryFn : ( ) => Promise . resolve ( id ) ,
100+ queryFn : ( ) => sleep ( 100 ) . then ( ( ) => id ) ,
99101 staleTime : 30_000 ,
100102 } ) ) ,
101103 combine : React . useCallback (
@@ -126,9 +128,9 @@ describe('useQueries with persist and memoized combine', () => {
126128 </ PersistQueryClientProvider > ,
127129 )
128130
129- await waitFor ( ( ) => {
130- expect ( getByTestId ( 'pending' ) . textContent ) . toBe ( 'false' )
131- expect ( getByTestId ( 'data ' ) . textContent ) . toBe ( '1,2,3 ' )
132- } )
131+ await act ( ( ) => vi . advanceTimersByTimeAsync ( 10 ) )
132+ await act ( ( ) => vi . advanceTimersByTimeAsync ( 0 ) )
133+ expect ( getByTestId ( 'pending ' ) . textContent ) . toBe ( 'false ' )
134+ expect ( getByTestId ( 'data' ) . textContent ) . toBe ( '1,2,3' )
133135 } )
134136} )
0 commit comments