File size: 6,627 Bytes
c2b7eb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import { createSlice, createAction } from '@reduxjs/toolkit'
import type { CombinedState } from '@reduxjs/toolkit/query'
import { createApi } from '@reduxjs/toolkit/query'
import { delay } from 'msw'
import { setupApiStore } from '../../tests/utils/helpers'

let shouldApiResponseSuccess = true

const rehydrateAction = createAction<{ api: CombinedState<any, any, any> }>(
  'persist/REHYDRATE',
)

const baseQuery = (args?: any) => ({ data: args })
const api = createApi({
  baseQuery,
  tagTypes: ['SUCCEED', 'FAILED'],
  endpoints: (build) => ({
    getUser: build.query<{ url: string; success: boolean }, number>({
      query(id) {
        return { url: `user/${id}`, success: shouldApiResponseSuccess }
      },
      providesTags: (result) => (result?.success ? ['SUCCEED'] : ['FAILED']),
    }),
  }),
  extractRehydrationInfo(action, { reducerPath }) {
    if (rehydrateAction.match(action)) {
      return action.payload?.[reducerPath]
    }
    return undefined
  },
})
const { getUser } = api.endpoints

const authSlice = createSlice({
  name: 'auth',
  initialState: {
    token: '1234',
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload
    },
  },
})

const storeRef = setupApiStore(api, { auth: authSlice.reducer })

describe('buildSlice', () => {
  beforeEach(() => {
    shouldApiResponseSuccess = true
  })

  it('only resets the api state when resetApiState is dispatched', async () => {
    storeRef.store.dispatch({ type: 'unrelated' }) // trigger "registered middleware" into place
    const initialState = storeRef.store.getState()

    await storeRef.store.dispatch(
      getUser.initiate(1, { subscriptionOptions: { pollingInterval: 10 } }),
    )

    const initialQueryState = {
      api: {
        config: {
          focused: true,
          invalidationBehavior: 'delayed',
          keepUnusedDataFor: 60,
          middlewareRegistered: true,
          online: true,
          reducerPath: 'api',
          refetchOnFocus: false,
          refetchOnMountOrArgChange: false,
          refetchOnReconnect: false,
        },
        mutations: {},
        provided: expect.any(Object),
        queries: {
          'getUser(1)': {
            data: {
              success: true,
              url: 'user/1',
            },
            endpointName: 'getUser',
            fulfilledTimeStamp: expect.any(Number),
            originalArgs: 1,
            requestId: expect.any(String),
            startedTimeStamp: expect.any(Number),
            status: 'fulfilled',
          },
        },
        // Filled some time later
        subscriptions: {},
      },
      auth: {
        token: '1234',
      },
    }

    expect(storeRef.store.getState()).toEqual(initialQueryState)

    storeRef.store.dispatch(api.util.resetApiState())

    expect(storeRef.store.getState()).toEqual(initialState)
  })

  it('replaces previous tags with new provided tags', async () => {
    await storeRef.store.dispatch(getUser.initiate(1))

    expect(
      api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),
    ).toHaveLength(1)
    expect(
      api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),
    ).toHaveLength(0)

    shouldApiResponseSuccess = false

    storeRef.store.dispatch(getUser.initiate(1)).refetch()

    await delay(10)

    expect(
      api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),
    ).toHaveLength(0)
    expect(
      api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),
    ).toHaveLength(1)
  })

  it('handles extractRehydrationInfo correctly', async () => {
    await storeRef.store.dispatch(getUser.initiate(1))
    await storeRef.store.dispatch(getUser.initiate(2))

    const stateWithUser = storeRef.store.getState()

    storeRef.store.dispatch(api.util.resetApiState())

    storeRef.store.dispatch(rehydrateAction({ api: stateWithUser.api }))

    const rehydratedState = storeRef.store.getState()
    expect(rehydratedState).toEqual(stateWithUser)
  })
})

describe('`merge` callback', () => {
  const baseQuery = (args?: any) => ({ data: args })

  interface Todo {
    id: string
    text: string
  }

  it('Calls `merge` once there is existing data, and allows mutations of cache state', async () => {
    let mergeCalled = false
    let queryFnCalls = 0
    const todoTexts = ['A', 'B', 'C', 'D']

    const api = createApi({
      baseQuery,
      endpoints: (build) => ({
        getTodos: build.query<Todo[], void>({
          async queryFn() {
            const text = todoTexts[queryFnCalls]
            return { data: [{ id: `${queryFnCalls++}`, text }] }
          },
          merge(currentCacheValue, responseData) {
            mergeCalled = true
            currentCacheValue.push(...responseData)
          },
        }),
      }),
    })

    const storeRef = setupApiStore(api, undefined, {
      withoutTestLifecycles: true,
    })

    const selectTodoEntry = api.endpoints.getTodos.select()

    const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())
    await res
    expect(mergeCalled).toBe(false)
    const todoEntry1 = selectTodoEntry(storeRef.store.getState())
    expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])

    res.refetch()

    await delay(10)

    expect(mergeCalled).toBe(true)
    const todoEntry2 = selectTodoEntry(storeRef.store.getState())

    expect(todoEntry2.data).toEqual([
      { id: '0', text: 'A' },
      { id: '1', text: 'B' },
    ])
  })

  it('Allows returning a different value from `merge`', async () => {
    let firstQueryFnCall = true

    const api = createApi({
      baseQuery,
      endpoints: (build) => ({
        getTodos: build.query<Todo[], void>({
          async queryFn() {
            const item = firstQueryFnCall
              ? { id: '0', text: 'A' }
              : { id: '1', text: 'B' }
            firstQueryFnCall = false
            return { data: [item] }
          },
          merge(currentCacheValue, responseData) {
            return responseData
          },
        }),
      }),
    })

    const storeRef = setupApiStore(api, undefined, {
      withoutTestLifecycles: true,
    })

    const selectTodoEntry = api.endpoints.getTodos.select()

    const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())
    await res

    const todoEntry1 = selectTodoEntry(storeRef.store.getState())
    expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])

    res.refetch()

    await delay(10)

    const todoEntry2 = selectTodoEntry(storeRef.store.getState())

    expect(todoEntry2.data).toEqual([{ id: '1', text: 'B' }])
  })
})