Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/src/query/tests/buildSlice.test.ts

raw
1 import { createSlice } from '@reduxjs/toolkit'
2 import { createApi } from '@reduxjs/toolkit/query'
3 import { delay } from 'msw'
4 import { setupApiStore } from '../../tests/utils/helpers'
5
6 let shouldApiResponseSuccess = true
7
8 const baseQuery = (args?: any) => ({ data: args })
9 const api = createApi({
10 baseQuery,
11 tagTypes: ['SUCCEED', 'FAILED'],
12 endpoints: (build) => ({
13 getUser: build.query<{ url: string; success: boolean }, number>({
14 query(id) {
15 return { url: `user/${id}`, success: shouldApiResponseSuccess }
16 },
17 providesTags: (result) => (result?.success ? ['SUCCEED'] : ['FAILED']),
18 }),
19 }),
20 })
21 const { getUser } = api.endpoints
22
23 const authSlice = createSlice({
24 name: 'auth',
25 initialState: {
26 token: '1234',
27 },
28 reducers: {
29 setToken(state, action) {
30 state.token = action.payload
31 },
32 },
33 })
34
35 const storeRef = setupApiStore(api, { auth: authSlice.reducer })
36
37 describe('buildSlice', () => {
38 beforeEach(() => {
39 shouldApiResponseSuccess = true
40 })
41
42 it('only resets the api state when resetApiState is dispatched', async () => {
43 storeRef.store.dispatch({ type: 'unrelated' }) // trigger "registered middleware" into place
44 const initialState = storeRef.store.getState()
45
46 await storeRef.store.dispatch(
47 getUser.initiate(1, { subscriptionOptions: { pollingInterval: 10 } }),
48 )
49
50 const initialQueryState = {
51 api: {
52 config: {
53 focused: true,
54 invalidationBehavior: 'delayed',
55 keepUnusedDataFor: 60,
56 middlewareRegistered: true,
57 online: true,
58 reducerPath: 'api',
59 refetchOnFocus: false,
60 refetchOnMountOrArgChange: false,
61 refetchOnReconnect: false,
62 },
63 mutations: {},
64 provided: expect.any(Object),
65 queries: {
66 'getUser(1)': {
67 data: {
68 success: true,
69 url: 'user/1',
70 },
71 endpointName: 'getUser',
72 fulfilledTimeStamp: expect.any(Number),
73 originalArgs: 1,
74 requestId: expect.any(String),
75 startedTimeStamp: expect.any(Number),
76 status: 'fulfilled',
77 },
78 },
79 // Filled some time later
80 subscriptions: {},
81 },
82 auth: {
83 token: '1234',
84 },
85 }
86
87 expect(storeRef.store.getState()).toEqual(initialQueryState)
88
89 storeRef.store.dispatch(api.util.resetApiState())
90
91 expect(storeRef.store.getState()).toEqual(initialState)
92 })
93
94 it('replaces previous tags with new provided tags', async () => {
95 await storeRef.store.dispatch(getUser.initiate(1))
96
97 expect(
98 api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),
99 ).toHaveLength(1)
100 expect(
101 api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),
102 ).toHaveLength(0)
103
104 shouldApiResponseSuccess = false
105
106 storeRef.store.dispatch(getUser.initiate(1)).refetch()
107
108 await delay(10)
109
110 expect(
111 api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),
112 ).toHaveLength(0)
113 expect(
114 api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),
115 ).toHaveLength(1)
116 })
117 })
118
119 describe('`merge` callback', () => {
120 const baseQuery = (args?: any) => ({ data: args })
121
122 interface Todo {
123 id: string
124 text: string
125 }
126
127 it('Calls `merge` once there is existing data, and allows mutations of cache state', async () => {
128 let mergeCalled = false
129 let queryFnCalls = 0
130 const todoTexts = ['A', 'B', 'C', 'D']
131
132 const api = createApi({
133 baseQuery,
134 endpoints: (build) => ({
135 getTodos: build.query<Todo[], void>({
136 async queryFn() {
137 const text = todoTexts[queryFnCalls]
138 return { data: [{ id: `${queryFnCalls++}`, text }] }
139 },
140 merge(currentCacheValue, responseData) {
141 mergeCalled = true
142 currentCacheValue.push(...responseData)
143 },
144 }),
145 }),
146 })
147
148 const storeRef = setupApiStore(api, undefined, {
149 withoutTestLifecycles: true,
150 })
151
152 const selectTodoEntry = api.endpoints.getTodos.select()
153
154 const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())
155 await res
156 expect(mergeCalled).toBe(false)
157 const todoEntry1 = selectTodoEntry(storeRef.store.getState())
158 expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])
159
160 res.refetch()
161
162 await delay(10)
163
164 expect(mergeCalled).toBe(true)
165 const todoEntry2 = selectTodoEntry(storeRef.store.getState())
166
167 expect(todoEntry2.data).toEqual([
168 { id: '0', text: 'A' },
169 { id: '1', text: 'B' },
170 ])
171 })
172
173 it('Allows returning a different value from `merge`', async () => {
174 let firstQueryFnCall = true
175
176 const api = createApi({
177 baseQuery,
178 endpoints: (build) => ({
179 getTodos: build.query<Todo[], void>({
180 async queryFn() {
181 const item = firstQueryFnCall
182 ? { id: '0', text: 'A' }
183 : { id: '1', text: 'B' }
184 firstQueryFnCall = false
185 return { data: [item] }
186 },
187 merge(currentCacheValue, responseData) {
188 return responseData
189 },
190 }),
191 }),
192 })
193
194 const storeRef = setupApiStore(api, undefined, {
195 withoutTestLifecycles: true,
196 })
197
198 const selectTodoEntry = api.endpoints.getTodos.select()
199
200 const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())
201 await res
202
203 const todoEntry1 = selectTodoEntry(storeRef.store.getState())
204 expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])
205
206 res.refetch()
207
208 await delay(10)
209
210 const todoEntry2 = selectTodoEntry(storeRef.store.getState())
211
212 expect(todoEntry2.data).toEqual([{ id: '1', text: 'B' }])
213 })
214 })