1
1
import { createApi } from '@reduxjs/toolkit/query/react'
2
2
import { actionsReducer , hookWaitFor , setupApiStore , waitMs } from './helpers'
3
3
import { renderHook , act } from '@testing-library/react'
4
+ import type { InvalidationState } from '../core/apiState'
4
5
5
6
interface Post {
6
7
id : string
@@ -26,6 +27,13 @@ const api = createApi({
26
27
query : ( id ) => `post/${ id } ` ,
27
28
providesTags : [ 'Post' ] ,
28
29
} ) ,
30
+ listPosts : build . query < Post [ ] , void > ( {
31
+ query : ( ) => `posts` ,
32
+ providesTags : ( result ) => [
33
+ ...( result ?. map ( ( { id } ) => ( { type : 'Post' as const , id } ) ) ?? [ ] ) ,
34
+ 'Post' ,
35
+ ] ,
36
+ } ) ,
29
37
updatePost : build . mutation < void , Pick < Post , 'id' > & Partial < Post > > ( {
30
38
query : ( { id, ...patch } ) => ( {
31
39
url : `post/${ id } ` ,
@@ -184,6 +192,67 @@ describe('updateQueryData', () => {
184
192
expect ( result . current . data ) . toEqual ( dataBefore )
185
193
} )
186
194
195
+ test . only ( 'updates cache values including provided tags, undos that' , async ( ) => {
196
+ baseQuery
197
+ . mockResolvedValueOnce ( [
198
+ {
199
+ id : '3' ,
200
+ title : 'All about cheese.' ,
201
+ contents : 'TODO' ,
202
+ } ,
203
+ ] )
204
+ . mockResolvedValueOnce ( 42 )
205
+ const { result } = renderHook ( ( ) => api . endpoints . listPosts . useQuery ( ) , {
206
+ wrapper : storeRef . wrapper ,
207
+ } )
208
+ await hookWaitFor ( ( ) => expect ( result . current . isSuccess ) . toBeTruthy ( ) )
209
+
210
+ let provided ! : InvalidationState < 'Post' >
211
+ act ( ( ) => {
212
+ provided = storeRef . store . getState ( ) . api . provided
213
+ } )
214
+
215
+ const provided3 = provided [ 'Post' ] [ '3' ]
216
+
217
+ let returnValue ! : ReturnType < ReturnType < typeof api . util . updateQueryData > >
218
+ act ( ( ) => {
219
+ returnValue = storeRef . store . dispatch (
220
+ api . util . updateQueryData (
221
+ 'listPosts' ,
222
+ undefined ,
223
+ ( draft ) => {
224
+ draft . push ( {
225
+ id : '4' ,
226
+ title : 'Mostly about cheese.' ,
227
+ contents : 'TODO' ,
228
+ } )
229
+ } ,
230
+ true
231
+ )
232
+ )
233
+ } )
234
+
235
+ act ( ( ) => {
236
+ provided = storeRef . store . getState ( ) . api . provided
237
+ } )
238
+
239
+ const provided4 = provided [ 'Post' ] [ '4' ]
240
+
241
+ expect ( provided4 ) . toEqual ( provided3 )
242
+
243
+ act ( ( ) => {
244
+ returnValue . undo ( )
245
+ } )
246
+
247
+ act ( ( ) => {
248
+ provided = storeRef . store . getState ( ) . api . provided
249
+ } )
250
+
251
+ const provided4Next = provided [ 'Post' ] [ '4' ]
252
+
253
+ expect ( provided4Next ) . toEqual ( [ ] )
254
+ } )
255
+
187
256
test ( 'does not update non-existing values' , async ( ) => {
188
257
baseQuery
189
258
. mockImplementationOnce ( async ( ) => ( {
0 commit comments