Test cache invalidation and reset
Inspect and test cache behavior
Test the behavior with a fresh store and known data. The API endpoint initiate method is useful outside React. Await a query result before reading its selected cache entry; unsubscribe from manually started queries when done. In the following fixture the result button runs actual RTK Query checks only when the dependencies are installed. Local authoring tests check pure helpers, not the integration.
import React, {useState} from 'react';import {configureStore} from '@reduxjs/toolkit';import {createApi, fakeBaseQuery} from '@reduxjs/toolkit/query/react';import {Provider, useDispatch} from 'react-redux';function initialRows(){return [{id:'lamp',name:'Lamp',quantity:4},{id:'chair',name:'Chair',quantity:2}];}function changeQuantity(rows,id,delta){ if(!Number.isInteger(delta)||Math.abs(delta)!==1)return {error:{code:'INVALID_DELTA'}}; const row=rows.find(item=>item.id===id); if(!row)return {error:{code:'NOT_FOUND'}}; if(row.quantity+delta<0)return {error:{code:'OUT_OF_STOCK'}}; return {data:rows.map(item=>item.id===id?{...item,quantity:item.quantity+delta}:item)};}function makeEnvironment(){ let rows=initialRows(); const api=createApi({reducerPath:'inventoryApi',baseQuery:fakeBaseQuery(),tagTypes:['Stock'],endpoints:build=>({ list:build.query({queryFn:async()=>({data:rows.map(item=>({...item}))}),providesTags:[{type:'Stock',id:'LIST'}]}), detail:build.query({queryFn:async(id)=>{const row=rows.find(x=>x.id===id);return row?{data:{...row}}:{error:{code:'NOT_FOUND'}};},providesTags:(_result,_error,id)=>[{type:'Stock',id}]}), adjust:build.mutation({queryFn:async({id,delta})=>{const result=changeQuantity(rows,id,delta);if(result.error)return result;rows=result.data;return {data:{...rows.find(x=>x.id===id)}};},invalidatesTags:(_result,error,{id})=>error?[]:[{type:'Stock',id},{type:'Stock',id:'LIST'}]}) })}); const store=configureStore({reducer:{[api.reducerPath]:api.reducer},middleware:gdm=>gdm().concat(api.middleware),devTools:false}); return {api,store};}
function Panel({api}){const dispatch=useDispatch();const [result,setResult]=useState('Not run');const [busy,setBusy]=useState(false);async function run(){setBusy(true);let list;try{list=dispatch(api.endpoints.list.initiate());const first=await list.unwrap();const changed=await dispatch(api.endpoints.adjust.initiate({id:'lamp',delta:1})).unwrap();const refreshed=await list.refetch().unwrap();setResult(refreshed.find(x=>x.id==='lamp').quantity===changed.quantity&&changed.quantity===first.find(x=>x.id==='lamp').quantity+1?'PASS':'FAIL');}catch{setResult('FAIL');}finally{list?.unsubscribe();setBusy(false);}}return <section><button disabled={busy} onClick={run}>Run cache scenario</button><p role="status">{result}</p></section>;}export default function App(){const [env]=useState(makeEnvironment);return <Provider store={env.store}><Panel api={env.api}/></Provider>;}This checks a successful mutation and an explicit refetch; it does not prove automatic invalidation by itself. To test automatic invalidation, keep a subscription active, dispatch the mutation, then wait with a bounded assertion for the selected query data to change without calling refetch. Test both successful and rejected writes, and inspect pending and fulfilled states using deferred mock promises. Default cache retention after the last subscriber leaves is 60 seconds unless configured otherwise. Retention and freshness are separate ideas.
Reset cache without pretending to reset the server
import React, {useState} from 'react';import {configureStore} from '@reduxjs/toolkit';import {createApi, fakeBaseQuery} from '@reduxjs/toolkit/query/react';import {Provider, useDispatch} from 'react-redux';function initialRows(){return [{id:'lamp',name:'Lamp',quantity:4},{id:'chair',name:'Chair',quantity:2}];}function changeQuantity(rows,id,delta){ if(!Number.isInteger(delta)||Math.abs(delta)!==1)return {error:{code:'INVALID_DELTA'}}; const row=rows.find(item=>item.id===id); if(!row)return {error:{code:'NOT_FOUND'}}; if(row.quantity+delta<0)return {error:{code:'OUT_OF_STOCK'}}; return {data:rows.map(item=>item.id===id?{...item,quantity:item.quantity+delta}:item)};}function makeEnvironment(){ let rows=initialRows(); const api=createApi({reducerPath:'inventoryApi',baseQuery:fakeBaseQuery(),tagTypes:['Stock'],endpoints:build=>({ list:build.query({queryFn:async()=>({data:rows.map(item=>({...item}))}),providesTags:[{type:'Stock',id:'LIST'}]}), detail:build.query({queryFn:async(id)=>{const row=rows.find(x=>x.id===id);return row?{data:{...row}}:{error:{code:'NOT_FOUND'}};},providesTags:(_result,_error,id)=>[{type:'Stock',id}]}), adjust:build.mutation({queryFn:async({id,delta})=>{const result=changeQuantity(rows,id,delta);if(result.error)return result;rows=result.data;return {data:{...rows.find(x=>x.id===id)}};},invalidatesTags:(_result,error,{id})=>error?[]:[{type:'Stock',id},{type:'Stock',id:'LIST'}]}) })}); const store=configureStore({reducer:{[api.reducerPath]:api.reducer},middleware:gdm=>gdm().concat(api.middleware),devTools:false}); return {api,store};}
function Panel({api}){const dispatch=useDispatch();const [status,setStatus]=useState('No cache test');const [busy,setBusy]=useState(false);async function run(){setBusy(true);const sub=dispatch(api.endpoints.detail.initiate('lamp'));try{await sub.unwrap();sub.unsubscribe();dispatch(api.util.resetApiState());setStatus('Cache reset; mock source unchanged');}catch{setStatus('Lookup failed');}finally{sub.unsubscribe();setBusy(false);}}return <section><button disabled={busy} onClick={run}>Read then reset cache</button><p role="status">{status}</p></section>;}export default function App(){const [env]=useState(makeEnvironment);return <Provider store={env.store}><Panel api={env.api}/></Provider>;}resetApiState clears the API slice cache, not the underlying inventory. Mounted Hooks may initiate requests again or retain some local Hook state, so this example has no mounted query subscriber. For logout, stop rendering private queries, cancel outstanding work where appropriate, clear private cache and replace the session-scoped store. A reset is not server-side revocation. Never hydrate another user’s private cached data; construct a fresh store for each SSR request and do not serialize sensitive data into HTML.
Check that independent environments do not share data
import React, {useState} from 'react';import {configureStore} from '@reduxjs/toolkit';import {createApi, fakeBaseQuery} from '@reduxjs/toolkit/query/react';import {Provider, useDispatch} from 'react-redux';function initialRows(){return [{id:'lamp',name:'Lamp',quantity:4},{id:'chair',name:'Chair',quantity:2}];}function changeQuantity(rows,id,delta){ if(!Number.isInteger(delta)||Math.abs(delta)!==1)return {error:{code:'INVALID_DELTA'}}; const row=rows.find(item=>item.id===id); if(!row)return {error:{code:'NOT_FOUND'}}; if(row.quantity+delta<0)return {error:{code:'OUT_OF_STOCK'}}; return {data:rows.map(item=>item.id===id?{...item,quantity:item.quantity+delta}:item)};}function makeEnvironment(){ let rows=initialRows(); const api=createApi({reducerPath:'inventoryApi',baseQuery:fakeBaseQuery(),tagTypes:['Stock'],endpoints:build=>({ list:build.query({queryFn:async()=>({data:rows.map(item=>({...item}))}),providesTags:[{type:'Stock',id:'LIST'}]}), detail:build.query({queryFn:async(id)=>{const row=rows.find(x=>x.id===id);return row?{data:{...row}}:{error:{code:'NOT_FOUND'}};},providesTags:(_result,_error,id)=>[{type:'Stock',id}]}), adjust:build.mutation({queryFn:async({id,delta})=>{const result=changeQuantity(rows,id,delta);if(result.error)return result;rows=result.data;return {data:{...rows.find(x=>x.id===id)}};},invalidatesTags:(_result,error,{id})=>error?[]:[{type:'Stock',id},{type:'Stock',id:'LIST'}]}) })}); const store=configureStore({reducer:{[api.reducerPath]:api.reducer},middleware:gdm=>gdm().concat(api.middleware),devTools:false}); return {api,store};}
function Panel(){const [status,setStatus]=useState('Not run');const [busy,setBusy]=useState(false);async function run(){setBusy(true);const a=makeEnvironment(),b=makeEnvironment();let left,right;try{await a.store.dispatch(a.api.endpoints.adjust.initiate({id:'lamp',delta:1})).unwrap();left=a.store.dispatch(a.api.endpoints.detail.initiate('lamp'));right=b.store.dispatch(b.api.endpoints.detail.initiate('lamp'));const [x,y]=await Promise.all([left.unwrap(),right.unwrap()]);setStatus(x.quantity===5&&y.quantity===4?'PASS: independent stores':'FAIL');}catch{setStatus('FAIL');}finally{left?.unsubscribe();right?.unsubscribe();a.store.dispatch(a.api.util.resetApiState());b.store.dispatch(b.api.util.resetApiState());setBusy(false);}}return <section><button disabled={busy} onClick={run}>Check isolation</button><p role="status">{status}</p></section>;}export default function App(){const [env]=useState(makeEnvironment);return <Provider store={env.store}><Panel api={env.api}/></Provider>;}Expected result: PASS: independent stores. The fixture creates a separate mock backend per environment for repeatable tests. Real users can share a backend while their frontend caches remain independent; authorization still belongs on the server. Use fresh stores for tests, not one global singleton. Choose an entity adapter for canonical client-owned records; use RTK Query for endpoint lifecycle, and avoid copying fetched data into a second store unless there is a specific editing or synchronization requirement.
Practice
Write a test plan for successful invalidation, failed mutation, unsubscribe and reset. Explain how to prove automatic refetching independently of explicit refetch, and why store reset does not delete server records.