@@ -294,4 +294,61 @@ describe('useSWR - refresh', () => {
294294 expect ( fetcherWithToken ) . toBeCalledTimes ( 5 )
295295 expect ( fetcherWithToken ) . toHaveBeenLastCalledWith ( '1' )
296296 } )
297+
298+ it ( 'the previous interval timer should not call onSuccess callback if key changes too fast' , async ( ) => {
299+ const fetcherWithToken = jest . fn ( async token => {
300+ await sleep ( 200 )
301+ return token
302+ } )
303+ const onSuccess = jest . fn ( ( data , key ) => {
304+ return `${ data } ${ key } `
305+ } )
306+ function Page ( ) {
307+ const [ count , setCount ] = useState ( 0 )
308+ const { data } = useSWR ( `${ count . toString ( ) } -hash` , fetcherWithToken , {
309+ refreshInterval : 100 ,
310+ dedupingInterval : 50 ,
311+ onSuccess
312+ } )
313+ return (
314+ < button
315+ onClick = { ( ) => setCount ( count + 1 ) }
316+ > { `click me ${ data } ` } </ button >
317+ )
318+ }
319+ const { container } = render ( < Page /> )
320+
321+ // initial revalidate
322+ await act ( ( ) => sleep ( 200 ) )
323+ expect ( fetcherWithToken ) . toBeCalledTimes ( 1 )
324+ expect ( onSuccess ) . toBeCalledTimes ( 1 )
325+ expect ( onSuccess ) . toHaveLastReturnedWith ( `0-hash 0-hash` )
326+ // first refresh
327+ await act ( ( ) => sleep ( 100 ) )
328+ expect ( fetcherWithToken ) . toBeCalledTimes ( 2 )
329+ expect ( fetcherWithToken ) . toHaveBeenLastCalledWith ( '0-hash' )
330+ await act ( ( ) => sleep ( 200 ) )
331+ expect ( onSuccess ) . toBeCalledTimes ( 2 )
332+ expect ( onSuccess ) . toHaveLastReturnedWith ( `0-hash 0-hash` )
333+
334+ // second refresh start
335+ await act ( ( ) => sleep ( 100 ) )
336+ expect ( fetcherWithToken ) . toBeCalledTimes ( 3 )
337+ expect ( fetcherWithToken ) . toHaveBeenLastCalledWith ( '0-hash' )
338+ // change the key during revalidation
339+ // The second refresh will not start a new timer
340+ fireEvent . click ( container . firstElementChild )
341+
342+ // first refresh with new key 1
343+ await act ( ( ) => sleep ( 100 ) )
344+ expect ( fetcherWithToken ) . toBeCalledTimes ( 4 )
345+ expect ( fetcherWithToken ) . toHaveBeenLastCalledWith ( '1-hash' )
346+ await act ( ( ) => sleep ( 210 ) )
347+ expect ( onSuccess ) . toBeCalledTimes ( 3 )
348+ expect ( onSuccess ) . toHaveLastReturnedWith ( `1-hash 1-hash` )
349+
350+ // second refresh with new key 1
351+ expect ( fetcherWithToken ) . toBeCalledTimes ( 5 )
352+ expect ( fetcherWithToken ) . toHaveBeenLastCalledWith ( '1-hash' )
353+ } )
297354} )
0 commit comments