| 1 |
import { noop } from '@internal/listenerMiddleware/utils' |
| 2 |
import type { SubscriptionOptions } from '@internal/query/core/apiState' |
| 3 |
import type { SubscriptionSelectors } from '@internal/query/core/buildMiddleware/types' |
| 4 |
import { server } from '@internal/query/tests/mocks/server' |
| 5 |
import { countObjectKeys } from '@internal/query/utils/countObjectKeys' |
| 6 |
import { |
| 7 |
actionsReducer, |
| 8 |
setupApiStore, |
| 9 |
useRenderCounter, |
| 10 |
waitForFakeTimer, |
| 11 |
waitMs, |
| 12 |
withProvider, |
| 13 |
} from '@internal/tests/utils/helpers' |
| 14 |
import type { UnknownAction } from '@reduxjs/toolkit' |
| 15 |
import { |
| 16 |
configureStore, |
| 17 |
createListenerMiddleware, |
| 18 |
createSlice, |
| 19 |
} from '@reduxjs/toolkit' |
| 20 |
import { |
| 21 |
QueryStatus, |
| 22 |
createApi, |
| 23 |
fetchBaseQuery, |
| 24 |
skipToken, |
| 25 |
} from '@reduxjs/toolkit/query/react' |
| 26 |
import { |
| 27 |
act, |
| 28 |
fireEvent, |
| 29 |
render, |
| 30 |
renderHook, |
| 31 |
screen, |
| 32 |
waitFor, |
| 33 |
} from '@testing-library/react' |
| 34 |
import { userEvent } from '@testing-library/user-event' |
| 35 |
import type { SyncScreen } from '@testing-library/react-render-stream/pure' |
| 36 |
import { createRenderStream } from '@testing-library/react-render-stream/pure' |
| 37 |
import { HttpResponse, http, delay } from 'msw' |
| 38 |
import { useEffect, useMemo, useState } from 'react' |
| 39 |
import type { InfiniteQueryResultFlags } from '../core/buildSelectors' |
| 40 |
|
| 41 |
// Just setup a temporary in-memory counter for tests that `getIncrementedAmount`. |
| 42 |
// This can be used to test how many renders happen due to data changes or |
| 43 |
// the refetching behavior of components. |
| 44 |
let amount = 0 |
| 45 |
let nextItemId = 0 |
| 46 |
let refetchCount = 0 |
| 47 |
|
| 48 |
interface Item { |
| 49 |
id: number |
| 50 |
} |
| 51 |
|
| 52 |
const api = createApi({ |
| 53 |
baseQuery: async (arg: any) => { |
| 54 |
await waitForFakeTimer(150) |
| 55 |
if (arg?.body && 'amount' in arg.body) { |
| 56 |
amount += 1 |
| 57 |
} |
| 58 |
|
| 59 |
if (arg?.body && 'forceError' in arg.body) { |
| 60 |
return { |
| 61 |
error: { |
| 62 |
status: 500, |
| 63 |
data: null, |
| 64 |
}, |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
if (arg?.body && 'listItems' in arg.body) { |
| 69 |
const items: Item[] = [] |
| 70 |
for (let i = 0; i < 3; i++) { |
| 71 |
const item = { id: nextItemId++ } |
| 72 |
items.push(item) |
| 73 |
} |
| 74 |
return { data: items } |
| 75 |
} |
| 76 |
|
| 77 |
return { |
| 78 |
data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : {}, |
| 79 |
} |
| 80 |
}, |
| 81 |
tagTypes: ['IncrementedAmount'], |
| 82 |
endpoints: (build) => ({ |
| 83 |
getUser: build.query<{ name: string }, number>({ |
| 84 |
query: () => ({ |
| 85 |
body: { name: 'Timmy' }, |
| 86 |
}), |
| 87 |
}), |
| 88 |
getUserAndForceError: build.query<{ name: string }, number>({ |
| 89 |
query: () => ({ |
| 90 |
body: { |
| 91 |
forceError: true, |
| 92 |
}, |
| 93 |
}), |
| 94 |
}), |
| 95 |
getUserWithRefetchError: build.query<{ name: string }, number>({ |
| 96 |
queryFn: async (id) => { |
| 97 |
refetchCount += 1 |
| 98 |
|
| 99 |
if (refetchCount > 1) { |
| 100 |
return { error: true } as any |
| 101 |
} |
| 102 |
|
| 103 |
return { data: { name: 'Timmy' } } |
| 104 |
}, |
| 105 |
}), |
| 106 |
getIncrementedAmount: build.query<{ amount: number }, void>({ |
| 107 |
query: () => ({ |
| 108 |
url: '', |
| 109 |
body: { |
| 110 |
amount, |
| 111 |
}, |
| 112 |
}), |
| 113 |
providesTags: ['IncrementedAmount'], |
| 114 |
}), |
| 115 |
triggerUpdatedAmount: build.mutation<void, void>({ |
| 116 |
queryFn: async () => { |
| 117 |
return { data: undefined } |
| 118 |
}, |
| 119 |
invalidatesTags: ['IncrementedAmount'], |
| 120 |
}), |
| 121 |
updateUser: build.mutation<{ name: string }, { name: string }>({ |
| 122 |
query: (update) => ({ body: update }), |
| 123 |
}), |
| 124 |
getError: build.query({ |
| 125 |
query: () => '/error', |
| 126 |
}), |
| 127 |
listItems: build.query<Item[], { pageNumber: number | bigint }>({ |
| 128 |
serializeQueryArgs: ({ endpointName }) => { |
| 129 |
return endpointName |
| 130 |
}, |
| 131 |
query: ({ pageNumber }) => ({ |
| 132 |
url: `items?limit=1&offset=${pageNumber}`, |
| 133 |
body: { |
| 134 |
listItems: true, |
| 135 |
}, |
| 136 |
}), |
| 137 |
merge: (currentCache, newItems) => { |
| 138 |
currentCache.push(...newItems) |
| 139 |
}, |
| 140 |
forceRefetch: () => { |
| 141 |
return true |
| 142 |
}, |
| 143 |
}), |
| 144 |
queryWithDeepArg: build.query<string, { param: { nested: string } }>({ |
| 145 |
query: ({ param: { nested } }) => nested, |
| 146 |
serializeQueryArgs: ({ queryArgs }) => { |
| 147 |
return queryArgs.param.nested |
| 148 |
}, |
| 149 |
}), |
| 150 |
}), |
| 151 |
}) |
| 152 |
|
| 153 |
const listenerMiddleware = createListenerMiddleware() |
| 154 |
|
| 155 |
let actions: UnknownAction[] = [] |
| 156 |
|
| 157 |
const storeRef = setupApiStore( |
| 158 |
api, |
| 159 |
{}, |
| 160 |
{ |
| 161 |
middleware: { |
| 162 |
prepend: [listenerMiddleware.middleware], |
| 163 |
}, |
| 164 |
}, |
| 165 |
) |
| 166 |
|
| 167 |
let getSubscriptions: SubscriptionSelectors['getSubscriptions'] |
| 168 |
let getSubscriptionCount: SubscriptionSelectors['getSubscriptionCount'] |
| 169 |
|
| 170 |
beforeEach(() => { |
| 171 |
actions = [] |
| 172 |
listenerMiddleware.startListening({ |
| 173 |
predicate: () => true, |
| 174 |
effect: (action) => { |
| 175 |
actions.push(action) |
| 176 |
}, |
| 177 |
}) |
| 178 |
;({ getSubscriptions, getSubscriptionCount } = storeRef.store.dispatch( |
| 179 |
api.internalActions.internal_getRTKQSubscriptions(), |
| 180 |
) as unknown as SubscriptionSelectors) |
| 181 |
}) |
| 182 |
|
| 183 |
afterEach(() => { |
| 184 |
nextItemId = 0 |
| 185 |
amount = 0 |
| 186 |
listenerMiddleware.clearListeners() |
| 187 |
|
| 188 |
server.resetHandlers() |
| 189 |
}) |
| 190 |
|
| 191 |
let getRenderCount: () => number = () => 0 |
| 192 |
|
| 193 |
describe('hooks tests', () => { |
| 194 |
describe('useQuery', () => { |
| 195 |
test('useQuery hook basic render count assumptions', async () => { |
| 196 |
function User() { |
| 197 |
const { isFetching } = api.endpoints.getUser.useQuery(1) |
| 198 |
getRenderCount = useRenderCounter() |
| 199 |
|
| 200 |
return ( |
| 201 |
<div> |
| 202 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 203 |
</div> |
| 204 |
) |
| 205 |
} |
| 206 |
|
| 207 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 208 |
// By the time this runs, the initial render will happen, and the query |
| 209 |
// will start immediately running by the time we can expect this |
| 210 |
expect(getRenderCount()).toBe(2) |
| 211 |
|
| 212 |
await waitFor(() => |
| 213 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 214 |
) |
| 215 |
expect(getRenderCount()).toBe(3) |
| 216 |
}) |
| 217 |
|
| 218 |
test('useQuery hook sets isFetching=true whenever a request is in flight', async () => { |
| 219 |
function User() { |
| 220 |
const [value, setValue] = useState(0) |
| 221 |
|
| 222 |
const { isFetching } = api.endpoints.getUser.useQuery(1, { |
| 223 |
skip: value < 1, |
| 224 |
}) |
| 225 |
getRenderCount = useRenderCounter() |
| 226 |
|
| 227 |
return ( |
| 228 |
<div> |
| 229 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 230 |
<button onClick={() => setValue((val) => val + 1)}> |
| 231 |
Increment value |
| 232 |
</button> |
| 233 |
</div> |
| 234 |
) |
| 235 |
} |
| 236 |
|
| 237 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 238 |
expect(getRenderCount()).toBe(1) |
| 239 |
|
| 240 |
await waitFor(() => |
| 241 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 242 |
) |
| 243 |
fireEvent.click(screen.getByText('Increment value')) // setState = 1, perform request = 2 |
| 244 |
await waitFor(() => |
| 245 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 246 |
) |
| 247 |
await waitFor(() => |
| 248 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 249 |
) |
| 250 |
expect(getRenderCount()).toBe(4) |
| 251 |
|
| 252 |
fireEvent.click(screen.getByText('Increment value')) |
| 253 |
// Being that nothing has changed in the args, this should never fire. |
| 254 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 255 |
expect(getRenderCount()).toBe(5) // even though there was no request, the button click updates the state so this is an expected render |
| 256 |
}) |
| 257 |
|
| 258 |
test('useQuery hook sets isLoading=true only on initial request', async () => { |
| 259 |
let refetch: any, isLoading: boolean, isFetching: boolean |
| 260 |
function User() { |
| 261 |
const [value, setValue] = useState(0) |
| 262 |
|
| 263 |
;({ isLoading, isFetching, refetch } = api.endpoints.getUser.useQuery( |
| 264 |
2, |
| 265 |
{ |
| 266 |
skip: value < 1, |
| 267 |
}, |
| 268 |
)) |
| 269 |
return ( |
| 270 |
<div> |
| 271 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 272 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 273 |
<button onClick={() => setValue((val) => val + 1)}> |
| 274 |
Increment value |
| 275 |
</button> |
| 276 |
</div> |
| 277 |
) |
| 278 |
} |
| 279 |
|
| 280 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 281 |
|
| 282 |
// Being that we skipped the initial request on mount, this should be false |
| 283 |
await waitFor(() => |
| 284 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 285 |
) |
| 286 |
fireEvent.click(screen.getByText('Increment value')) |
| 287 |
// Condition is met, should load |
| 288 |
await waitFor(() => |
| 289 |
expect(screen.getByTestId('isLoading').textContent).toBe('true'), |
| 290 |
) |
| 291 |
await waitFor(() => |
| 292 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 293 |
) // Make sure the original loading has completed. |
| 294 |
fireEvent.click(screen.getByText('Increment value')) |
| 295 |
// Being that we already have data, isLoading should be false |
| 296 |
await waitFor(() => |
| 297 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 298 |
) |
| 299 |
// We call a refetch, should still be `false` |
| 300 |
act(() => void refetch()) |
| 301 |
await waitFor(() => |
| 302 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 303 |
) |
| 304 |
expect(screen.getByTestId('isLoading').textContent).toBe('false') |
| 305 |
}) |
| 306 |
|
| 307 |
test('useQuery hook sets isLoading and isFetching to the correct states', async () => { |
| 308 |
let refetchMe: () => void = () => {} |
| 309 |
function User() { |
| 310 |
const [value, setValue] = useState(0) |
| 311 |
getRenderCount = useRenderCounter() |
| 312 |
|
| 313 |
const { isLoading, isFetching, refetch } = |
| 314 |
api.endpoints.getUser.useQuery(22, { skip: value < 1 }) |
| 315 |
refetchMe = refetch |
| 316 |
return ( |
| 317 |
<div> |
| 318 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 319 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 320 |
<button onClick={() => setValue((val) => val + 1)}> |
| 321 |
Increment value |
| 322 |
</button> |
| 323 |
</div> |
| 324 |
) |
| 325 |
} |
| 326 |
|
| 327 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 328 |
expect(getRenderCount()).toBe(1) |
| 329 |
|
| 330 |
expect(screen.getByTestId('isLoading').textContent).toBe('false') |
| 331 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 332 |
|
| 333 |
fireEvent.click(screen.getByText('Increment value')) // renders: set state = 1, perform request = 2 |
| 334 |
// Condition is met, should load |
| 335 |
await waitFor(() => { |
| 336 |
expect(screen.getByTestId('isLoading').textContent).toBe('true') |
| 337 |
expect(screen.getByTestId('isFetching').textContent).toBe('true') |
| 338 |
}) |
| 339 |
|
| 340 |
// Make sure the request is done for sure. |
| 341 |
await waitFor(() => { |
| 342 |
expect(screen.getByTestId('isLoading').textContent).toBe('false') |
| 343 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 344 |
}) |
| 345 |
expect(getRenderCount()).toBe(4) |
| 346 |
|
| 347 |
fireEvent.click(screen.getByText('Increment value')) |
| 348 |
// Being that we already have data and changing the value doesn't trigger a new request, only the button click should impact the render |
| 349 |
await waitFor(() => { |
| 350 |
expect(screen.getByTestId('isLoading').textContent).toBe('false') |
| 351 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 352 |
}) |
| 353 |
expect(getRenderCount()).toBe(5) |
| 354 |
|
| 355 |
// We call a refetch, should set `isFetching` to true, then false when complete/errored |
| 356 |
act(() => void refetchMe()) |
| 357 |
await waitFor(() => { |
| 358 |
expect(screen.getByTestId('isLoading').textContent).toBe('false') |
| 359 |
expect(screen.getByTestId('isFetching').textContent).toBe('true') |
| 360 |
}) |
| 361 |
await waitFor(() => { |
| 362 |
expect(screen.getByTestId('isLoading').textContent).toBe('false') |
| 363 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 364 |
}) |
| 365 |
expect(getRenderCount()).toBe(7) |
| 366 |
}) |
| 367 |
|
| 368 |
test('`isLoading` does not jump back to true, while `isFetching` does', async () => { |
| 369 |
const loadingHist: boolean[] = [], |
| 370 |
fetchingHist: boolean[] = [] |
| 371 |
|
| 372 |
function User({ id }: { id: number }) { |
| 373 |
const { isLoading, isFetching, status } = |
| 374 |
api.endpoints.getUser.useQuery(id) |
| 375 |
|
| 376 |
useEffect(() => { |
| 377 |
loadingHist.push(isLoading) |
| 378 |
}, [isLoading]) |
| 379 |
useEffect(() => { |
| 380 |
fetchingHist.push(isFetching) |
| 381 |
}, [isFetching]) |
| 382 |
return ( |
| 383 |
<div data-testid="status"> |
| 384 |
{status === QueryStatus.fulfilled && id} |
| 385 |
</div> |
| 386 |
) |
| 387 |
} |
| 388 |
|
| 389 |
let { rerender } = render(<User id={1} />, { wrapper: storeRef.wrapper }) |
| 390 |
|
| 391 |
await waitFor(() => |
| 392 |
expect(screen.getByTestId('status').textContent).toBe('1'), |
| 393 |
) |
| 394 |
rerender(<User id={2} />) |
| 395 |
|
| 396 |
await waitFor(() => |
| 397 |
expect(screen.getByTestId('status').textContent).toBe('2'), |
| 398 |
) |
| 399 |
|
| 400 |
expect(loadingHist).toEqual([true, false]) |
| 401 |
expect(fetchingHist).toEqual([true, false, true, false]) |
| 402 |
}) |
| 403 |
|
| 404 |
test('`isSuccess` does not jump back false on subsequent queries', async () => { |
| 405 |
type LoadingState = { |
| 406 |
id: number |
| 407 |
isFetching: boolean |
| 408 |
isSuccess: boolean |
| 409 |
} |
| 410 |
const loadingHistory: LoadingState[] = [] |
| 411 |
|
| 412 |
function User({ id }: { id: number }) { |
| 413 |
const queryRes = api.endpoints.getUser.useQuery(id) |
| 414 |
|
| 415 |
useEffect(() => { |
| 416 |
const { isFetching, isSuccess } = queryRes |
| 417 |
loadingHistory.push({ id, isFetching, isSuccess }) |
| 418 |
}, [id, queryRes]) |
| 419 |
return ( |
| 420 |
<div data-testid="status"> |
| 421 |
{queryRes.status === QueryStatus.fulfilled && id} |
| 422 |
</div> |
| 423 |
) |
| 424 |
} |
| 425 |
|
| 426 |
let { rerender } = render(<User id={1} />, { wrapper: storeRef.wrapper }) |
| 427 |
|
| 428 |
await waitFor(() => |
| 429 |
expect(screen.getByTestId('status').textContent).toBe('1'), |
| 430 |
) |
| 431 |
rerender(<User id={2} />) |
| 432 |
|
| 433 |
await waitFor(() => |
| 434 |
expect(screen.getByTestId('status').textContent).toBe('2'), |
| 435 |
) |
| 436 |
|
| 437 |
expect(loadingHistory).toEqual([ |
| 438 |
// Initial render(s) |
| 439 |
{ id: 1, isFetching: true, isSuccess: false }, |
| 440 |
{ id: 1, isFetching: true, isSuccess: false }, |
| 441 |
// Data returned |
| 442 |
{ id: 1, isFetching: false, isSuccess: true }, |
| 443 |
// ID changed, there's an uninitialized cache entry. |
| 444 |
// IMPORTANT: `isSuccess` should not be false here. |
| 445 |
// We have valid data already for the old item. |
| 446 |
{ id: 2, isFetching: true, isSuccess: true }, |
| 447 |
{ id: 2, isFetching: true, isSuccess: true }, |
| 448 |
{ id: 2, isFetching: false, isSuccess: true }, |
| 449 |
]) |
| 450 |
}) |
| 451 |
|
| 452 |
test('isSuccess stays consistent if there is an error while refetching', async () => { |
| 453 |
type LoadingState = { |
| 454 |
id: number |
| 455 |
isFetching: boolean |
| 456 |
isSuccess: boolean |
| 457 |
isError: boolean |
| 458 |
} |
| 459 |
const loadingHistory: LoadingState[] = [] |
| 460 |
|
| 461 |
function Component({ id = 1 }) { |
| 462 |
const queryRes = api.endpoints.getUserWithRefetchError.useQuery(id) |
| 463 |
const { refetch, data, status } = queryRes |
| 464 |
|
| 465 |
useEffect(() => { |
| 466 |
const { isFetching, isSuccess, isError } = queryRes |
| 467 |
loadingHistory.push({ id, isFetching, isSuccess, isError }) |
| 468 |
}, [id, queryRes]) |
| 469 |
|
| 470 |
return ( |
| 471 |
<div> |
| 472 |
<button |
| 473 |
onClick={() => { |
| 474 |
refetch() |
| 475 |
}} |
| 476 |
> |
| 477 |
refetch |
| 478 |
</button> |
| 479 |
<div data-testid="name">{data?.name}</div> |
| 480 |
<div data-testid="status">{status}</div> |
| 481 |
</div> |
| 482 |
) |
| 483 |
} |
| 484 |
|
| 485 |
render(<Component />, { wrapper: storeRef.wrapper }) |
| 486 |
|
| 487 |
await waitFor(() => |
| 488 |
expect(screen.getByTestId('name').textContent).toBe('Timmy'), |
| 489 |
) |
| 490 |
|
| 491 |
fireEvent.click(screen.getByText('refetch')) |
| 492 |
|
| 493 |
await waitFor(() => |
| 494 |
expect(screen.getByTestId('status').textContent).toBe('pending'), |
| 495 |
) |
| 496 |
|
| 497 |
await waitFor(() => |
| 498 |
expect(screen.getByTestId('status').textContent).toBe('rejected'), |
| 499 |
) |
| 500 |
|
| 501 |
fireEvent.click(screen.getByText('refetch')) |
| 502 |
|
| 503 |
await waitFor(() => |
| 504 |
expect(screen.getByTestId('status').textContent).toBe('pending'), |
| 505 |
) |
| 506 |
|
| 507 |
await waitFor(() => |
| 508 |
expect(screen.getByTestId('status').textContent).toBe('rejected'), |
| 509 |
) |
| 510 |
|
| 511 |
expect(loadingHistory).toEqual([ |
| 512 |
// Initial renders |
| 513 |
{ id: 1, isFetching: true, isSuccess: false, isError: false }, |
| 514 |
{ id: 1, isFetching: true, isSuccess: false, isError: false }, |
| 515 |
// Data is returned |
| 516 |
{ id: 1, isFetching: false, isSuccess: true, isError: false }, |
| 517 |
// Started first refetch |
| 518 |
{ id: 1, isFetching: true, isSuccess: true, isError: false }, |
| 519 |
// First refetch errored |
| 520 |
{ id: 1, isFetching: false, isSuccess: false, isError: true }, |
| 521 |
// Started second refetch |
| 522 |
// IMPORTANT We expect `isSuccess` to still be false, |
| 523 |
// despite having started the refetch again. |
| 524 |
{ id: 1, isFetching: true, isSuccess: false, isError: false }, |
| 525 |
// Second refetch errored |
| 526 |
{ id: 1, isFetching: false, isSuccess: false, isError: true }, |
| 527 |
]) |
| 528 |
}) |
| 529 |
|
| 530 |
test('useQuery hook respects refetchOnMountOrArgChange: true', async () => { |
| 531 |
let data, isLoading, isFetching |
| 532 |
function User() { |
| 533 |
;({ data, isLoading, isFetching } = |
| 534 |
api.endpoints.getIncrementedAmount.useQuery(undefined, { |
| 535 |
refetchOnMountOrArgChange: true, |
| 536 |
})) |
| 537 |
return ( |
| 538 |
<div> |
| 539 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 540 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 541 |
<div data-testid="amount">{String(data?.amount)}</div> |
| 542 |
</div> |
| 543 |
) |
| 544 |
} |
| 545 |
|
| 546 |
const { unmount } = render(<User />, { wrapper: storeRef.wrapper }) |
| 547 |
|
| 548 |
await waitFor(() => |
| 549 |
expect(screen.getByTestId('isLoading').textContent).toBe('true'), |
| 550 |
) |
| 551 |
await waitFor(() => |
| 552 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 553 |
) |
| 554 |
|
| 555 |
await waitFor(() => |
| 556 |
expect(screen.getByTestId('amount').textContent).toBe('1'), |
| 557 |
) |
| 558 |
|
| 559 |
unmount() |
| 560 |
|
| 561 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 562 |
// Let's make sure we actually fetch, and we increment |
| 563 |
expect(screen.getByTestId('isLoading').textContent).toBe('false') |
| 564 |
await waitFor(() => |
| 565 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 566 |
) |
| 567 |
await waitFor(() => |
| 568 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 569 |
) |
| 570 |
|
| 571 |
await waitFor(() => |
| 572 |
expect(screen.getByTestId('amount').textContent).toBe('2'), |
| 573 |
) |
| 574 |
}) |
| 575 |
|
| 576 |
test('useQuery does not refetch when refetchOnMountOrArgChange: NUMBER condition is not met', async () => { |
| 577 |
let data, isLoading, isFetching |
| 578 |
function User() { |
| 579 |
;({ data, isLoading, isFetching } = |
| 580 |
api.endpoints.getIncrementedAmount.useQuery(undefined, { |
| 581 |
refetchOnMountOrArgChange: 10, |
| 582 |
})) |
| 583 |
return ( |
| 584 |
<div> |
| 585 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 586 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 587 |
<div data-testid="amount">{String(data?.amount)}</div> |
| 588 |
</div> |
| 589 |
) |
| 590 |
} |
| 591 |
|
| 592 |
const { unmount } = render(<User />, { wrapper: storeRef.wrapper }) |
| 593 |
|
| 594 |
await waitFor(() => |
| 595 |
expect(screen.getByTestId('isLoading').textContent).toBe('true'), |
| 596 |
) |
| 597 |
await waitFor(() => |
| 598 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 599 |
) |
| 600 |
|
| 601 |
await waitFor(() => |
| 602 |
expect(screen.getByTestId('amount').textContent).toBe('1'), |
| 603 |
) |
| 604 |
|
| 605 |
unmount() |
| 606 |
|
| 607 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 608 |
// Let's make sure we actually fetch, and we increment. Should be false because we do this immediately |
| 609 |
// and the condition is set to 10 seconds |
| 610 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 611 |
await waitFor(() => |
| 612 |
expect(screen.getByTestId('amount').textContent).toBe('1'), |
| 613 |
) |
| 614 |
}) |
| 615 |
|
| 616 |
test('useQuery refetches when refetchOnMountOrArgChange: NUMBER condition is met', async () => { |
| 617 |
let data, isLoading, isFetching |
| 618 |
function User() { |
| 619 |
;({ data, isLoading, isFetching } = |
| 620 |
api.endpoints.getIncrementedAmount.useQuery(undefined, { |
| 621 |
refetchOnMountOrArgChange: 0.5, |
| 622 |
})) |
| 623 |
return ( |
| 624 |
<div> |
| 625 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 626 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 627 |
<div data-testid="amount">{String(data?.amount)}</div> |
| 628 |
</div> |
| 629 |
) |
| 630 |
} |
| 631 |
|
| 632 |
const { unmount } = render(<User />, { wrapper: storeRef.wrapper }) |
| 633 |
|
| 634 |
await waitFor(() => |
| 635 |
expect(screen.getByTestId('isLoading').textContent).toBe('true'), |
| 636 |
) |
| 637 |
await waitFor(() => |
| 638 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 639 |
) |
| 640 |
|
| 641 |
await waitFor(() => |
| 642 |
expect(screen.getByTestId('amount').textContent).toBe('1'), |
| 643 |
) |
| 644 |
|
| 645 |
unmount() |
| 646 |
|
| 647 |
// Wait to make sure we've passed the `refetchOnMountOrArgChange` value |
| 648 |
await waitMs(510) |
| 649 |
|
| 650 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 651 |
// Let's make sure we actually fetch, and we increment |
| 652 |
await waitFor(() => |
| 653 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 654 |
) |
| 655 |
await waitFor(() => |
| 656 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 657 |
) |
| 658 |
|
| 659 |
await waitFor(() => |
| 660 |
expect(screen.getByTestId('amount').textContent).toBe('2'), |
| 661 |
) |
| 662 |
}) |
| 663 |
|
| 664 |
test('refetchOnMountOrArgChange works as expected when changing skip from false->true', async () => { |
| 665 |
let data, isLoading, isFetching |
| 666 |
function User() { |
| 667 |
const [skip, setSkip] = useState(true) |
| 668 |
;({ data, isLoading, isFetching } = |
| 669 |
api.endpoints.getIncrementedAmount.useQuery(undefined, { |
| 670 |
refetchOnMountOrArgChange: 0.5, |
| 671 |
skip, |
| 672 |
})) |
| 673 |
|
| 674 |
return ( |
| 675 |
<div> |
| 676 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 677 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 678 |
<div data-testid="amount">{String(data?.amount)}</div> |
| 679 |
<button onClick={() => setSkip((prev) => !prev)}> |
| 680 |
change skip |
| 681 |
</button> |
| 682 |
; |
| 683 |
</div> |
| 684 |
) |
| 685 |
} |
| 686 |
|
| 687 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 688 |
|
| 689 |
expect(screen.getByTestId('isLoading').textContent).toBe('false') |
| 690 |
expect(screen.getByTestId('amount').textContent).toBe('undefined') |
| 691 |
|
| 692 |
fireEvent.click(screen.getByText('change skip')) |
| 693 |
|
| 694 |
await waitFor(() => |
| 695 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 696 |
) |
| 697 |
await waitFor(() => |
| 698 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 699 |
) |
| 700 |
|
| 701 |
await waitFor(() => |
| 702 |
expect(screen.getByTestId('amount').textContent).toBe('1'), |
| 703 |
) |
| 704 |
}) |
| 705 |
|
| 706 |
test('refetchOnMountOrArgChange works as expected when changing skip from false->true with a cached query', async () => { |
| 707 |
// 1. we need to mount a skipped query, then toggle skip to generate a cached result |
| 708 |
// 2. we need to mount a skipped component after that, then toggle skip as well. should pull from the cache. |
| 709 |
// 3. we need to mount another skipped component, then toggle skip after the specified duration and expect the time condition to be satisfied |
| 710 |
|
| 711 |
let data, isLoading, isFetching |
| 712 |
function User() { |
| 713 |
const [skip, setSkip] = useState(true) |
| 714 |
;({ data, isLoading, isFetching } = |
| 715 |
api.endpoints.getIncrementedAmount.useQuery(undefined, { |
| 716 |
skip, |
| 717 |
refetchOnMountOrArgChange: 0.5, |
| 718 |
})) |
| 719 |
|
| 720 |
return ( |
| 721 |
<div> |
| 722 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 723 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 724 |
<div data-testid="amount">{String(data?.amount)}</div> |
| 725 |
<button onClick={() => setSkip((prev) => !prev)}> |
| 726 |
change skip |
| 727 |
</button> |
| 728 |
; |
| 729 |
</div> |
| 730 |
) |
| 731 |
} |
| 732 |
|
| 733 |
let { unmount } = render(<User />, { wrapper: storeRef.wrapper }) |
| 734 |
|
| 735 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 736 |
|
| 737 |
// skipped queries do nothing by default, so we need to toggle that to get a cached result |
| 738 |
fireEvent.click(screen.getByText('change skip')) |
| 739 |
|
| 740 |
await waitFor(() => |
| 741 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 742 |
) |
| 743 |
|
| 744 |
await waitFor(() => { |
| 745 |
expect(screen.getByTestId('amount').textContent).toBe('1') |
| 746 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 747 |
}) |
| 748 |
|
| 749 |
unmount() |
| 750 |
|
| 751 |
await waitMs(100) |
| 752 |
|
| 753 |
// This will pull from the cache as the time criteria is not met. |
| 754 |
;({ unmount } = render(<User />, { |
| 755 |
wrapper: storeRef.wrapper, |
| 756 |
})) |
| 757 |
|
| 758 |
// skipped queries return nothing |
| 759 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 760 |
expect(screen.getByTestId('amount').textContent).toBe('undefined') |
| 761 |
|
| 762 |
// toggle skip -> true... won't refetch as the time critera is not met, and just loads the cached values |
| 763 |
fireEvent.click(screen.getByText('change skip')) |
| 764 |
expect(screen.getByTestId('isFetching').textContent).toBe('false') |
| 765 |
expect(screen.getByTestId('amount').textContent).toBe('1') |
| 766 |
|
| 767 |
unmount() |
| 768 |
|
| 769 |
await waitMs(500) |
| 770 |
;({ unmount } = render(<User />, { |
| 771 |
wrapper: storeRef.wrapper, |
| 772 |
})) |
| 773 |
|
| 774 |
// toggle skip -> true... will cause a refetch as the time criteria is now satisfied |
| 775 |
fireEvent.click(screen.getByText('change skip')) |
| 776 |
|
| 777 |
await waitFor(() => |
| 778 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 779 |
) |
| 780 |
await waitFor(() => |
| 781 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 782 |
) |
| 783 |
|
| 784 |
await waitFor(() => |
| 785 |
expect(screen.getByTestId('amount').textContent).toBe('2'), |
| 786 |
) |
| 787 |
}) |
| 788 |
|
| 789 |
test(`useQuery refetches when query args object changes even if serialized args don't change`, async () => { |
| 790 |
const user = userEvent.setup() |
| 791 |
|
| 792 |
function ItemList() { |
| 793 |
const [pageNumber, setPageNumber] = useState(0) |
| 794 |
const { data = [] } = api.useListItemsQuery({ |
| 795 |
pageNumber, |
| 796 |
}) |
| 797 |
|
| 798 |
const renderedItems = data.map((item) => ( |
| 799 |
<li key={item.id}>ID: {item.id}</li> |
| 800 |
)) |
| 801 |
return ( |
| 802 |
<div> |
| 803 |
<button onClick={() => setPageNumber(pageNumber + 1)}> |
| 804 |
Next Page |
| 805 |
</button> |
| 806 |
<ul>{renderedItems}</ul> |
| 807 |
</div> |
| 808 |
) |
| 809 |
} |
| 810 |
|
| 811 |
render(<ItemList />, { wrapper: storeRef.wrapper }) |
| 812 |
|
| 813 |
await screen.findByText('ID: 0') |
| 814 |
|
| 815 |
await user.click(screen.getByText('Next Page')) |
| 816 |
|
| 817 |
await screen.findByText('ID: 3') |
| 818 |
}) |
| 819 |
|
| 820 |
test(`useQuery shouldn't call args serialization if request skipped`, async () => { |
| 821 |
expect(() => |
| 822 |
renderHook(() => api.endpoints.queryWithDeepArg.useQuery(skipToken), { |
| 823 |
wrapper: storeRef.wrapper, |
| 824 |
}), |
| 825 |
).not.toThrow() |
| 826 |
}) |
| 827 |
|
| 828 |
test(`useQuery gracefully handles bigint types`, async () => { |
| 829 |
const user = userEvent.setup() |
| 830 |
|
| 831 |
function ItemList() { |
| 832 |
const [pageNumber, setPageNumber] = useState(0) |
| 833 |
const { data = [] } = api.useListItemsQuery({ |
| 834 |
pageNumber: BigInt(pageNumber), |
| 835 |
}) |
| 836 |
|
| 837 |
const renderedItems = data.map((item) => ( |
| 838 |
<li key={item.id}>ID: {item.id}</li> |
| 839 |
)) |
| 840 |
return ( |
| 841 |
<div> |
| 842 |
<button onClick={() => setPageNumber(pageNumber + 1)}> |
| 843 |
Next Page |
| 844 |
</button> |
| 845 |
<ul>{renderedItems}</ul> |
| 846 |
</div> |
| 847 |
) |
| 848 |
} |
| 849 |
|
| 850 |
render(<ItemList />, { wrapper: storeRef.wrapper }) |
| 851 |
|
| 852 |
await screen.findByText('ID: 0') |
| 853 |
|
| 854 |
await user.click(screen.getByText('Next Page')) |
| 855 |
|
| 856 |
await screen.findByText('ID: 3') |
| 857 |
}) |
| 858 |
|
| 859 |
describe('api.util.resetApiState resets hook', () => { |
| 860 |
test('without `selectFromResult`', async () => { |
| 861 |
const { result } = renderHook(() => api.endpoints.getUser.useQuery(5), { |
| 862 |
wrapper: storeRef.wrapper, |
| 863 |
}) |
| 864 |
|
| 865 |
await waitFor(() => expect(result.current.isSuccess).toBe(true)) |
| 866 |
|
| 867 |
act(() => void storeRef.store.dispatch(api.util.resetApiState())) |
| 868 |
|
| 869 |
expect(result.current).toEqual( |
| 870 |
expect.objectContaining({ |
| 871 |
isError: false, |
| 872 |
isFetching: true, |
| 873 |
isLoading: true, |
| 874 |
isSuccess: false, |
| 875 |
isUninitialized: false, |
| 876 |
refetch: expect.any(Function), |
| 877 |
status: 'pending', |
| 878 |
}), |
| 879 |
) |
| 880 |
}) |
| 881 |
test('with `selectFromResult`', async () => { |
| 882 |
const selectFromResult = vi.fn((x) => x) |
| 883 |
const { result } = renderHook( |
| 884 |
() => api.endpoints.getUser.useQuery(5, { selectFromResult }), |
| 885 |
{ |
| 886 |
wrapper: storeRef.wrapper, |
| 887 |
}, |
| 888 |
) |
| 889 |
|
| 890 |
await waitFor(() => expect(result.current.isSuccess).toBe(true)) |
| 891 |
selectFromResult.mockClear() |
| 892 |
act(() => { |
| 893 |
storeRef.store.dispatch(api.util.resetApiState()) |
| 894 |
}) |
| 895 |
|
| 896 |
expect(selectFromResult).toHaveBeenNthCalledWith(1, { |
| 897 |
isError: false, |
| 898 |
isFetching: false, |
| 899 |
isLoading: false, |
| 900 |
isSuccess: false, |
| 901 |
isUninitialized: true, |
| 902 |
status: 'uninitialized', |
| 903 |
}) |
| 904 |
}) |
| 905 |
}) |
| 906 |
|
| 907 |
test('useQuery refetch method returns a promise that resolves with the result', async () => { |
| 908 |
const { result } = renderHook( |
| 909 |
() => api.endpoints.getIncrementedAmount.useQuery(), |
| 910 |
{ |
| 911 |
wrapper: storeRef.wrapper, |
| 912 |
}, |
| 913 |
) |
| 914 |
|
| 915 |
await waitFor(() => expect(result.current.isSuccess).toBe(true)) |
| 916 |
const originalAmount = result.current.data!.amount |
| 917 |
|
| 918 |
const { refetch } = result.current |
| 919 |
|
| 920 |
let resPromise: ReturnType<typeof refetch> = null as any |
| 921 |
await act(async () => { |
| 922 |
resPromise = refetch() |
| 923 |
}) |
| 924 |
expect(resPromise).toBeInstanceOf(Promise) |
| 925 |
const res = await act(() => resPromise) |
| 926 |
expect(res.data!.amount).toBeGreaterThan(originalAmount) |
| 927 |
}) |
| 928 |
|
| 929 |
// See https://github.com/reduxjs/redux-toolkit/issues/4267 - Memory leak in useQuery rapid query arg changes |
| 930 |
test('Hook subscriptions are properly cleaned up when query is fulfilled/rejected', async () => { |
| 931 |
// This is imported already, but it seems to be causing issues with the test on certain matrixes |
| 932 |
|
| 933 |
const pokemonApi = createApi({ |
| 934 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }), |
| 935 |
endpoints: (builder) => ({ |
| 936 |
getTest: builder.query<string, number>({ |
| 937 |
async queryFn() { |
| 938 |
await new Promise((resolve) => setTimeout(resolve, 1000)) |
| 939 |
return { data: 'data!' } |
| 940 |
}, |
| 941 |
keepUnusedDataFor: 0, |
| 942 |
}), |
| 943 |
}), |
| 944 |
}) |
| 945 |
|
| 946 |
const storeRef = setupApiStore(pokemonApi, undefined, { |
| 947 |
withoutTestLifecycles: true, |
| 948 |
}) |
| 949 |
|
| 950 |
const checkNumQueries = (count: number) => { |
| 951 |
const cacheEntries = Object.keys(storeRef.store.getState().api.queries) |
| 952 |
const queries = cacheEntries.length |
| 953 |
|
| 954 |
expect(queries).toBe(count) |
| 955 |
} |
| 956 |
|
| 957 |
let i = 0 |
| 958 |
|
| 959 |
function User() { |
| 960 |
const [fetchTest, { isFetching, isUninitialized }] = |
| 961 |
pokemonApi.endpoints.getTest.useLazyQuery() |
| 962 |
|
| 963 |
return ( |
| 964 |
<div> |
| 965 |
<div data-testid="isUninitialized">{String(isUninitialized)}</div> |
| 966 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 967 |
<button data-testid="fetchButton" onClick={() => fetchTest(i++)}> |
| 968 |
fetchUser |
| 969 |
</button> |
| 970 |
</div> |
| 971 |
) |
| 972 |
} |
| 973 |
|
| 974 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 975 |
fireEvent.click(screen.getByTestId('fetchButton')) |
| 976 |
fireEvent.click(screen.getByTestId('fetchButton')) |
| 977 |
fireEvent.click(screen.getByTestId('fetchButton')) |
| 978 |
checkNumQueries(3) |
| 979 |
|
| 980 |
await act(async () => { |
| 981 |
await delay(1500) |
| 982 |
}) |
| 983 |
|
| 984 |
// There should only be one stored query once they have had time to resolve |
| 985 |
checkNumQueries(1) |
| 986 |
}) |
| 987 |
|
| 988 |
// See https://github.com/reduxjs/redux-toolkit/issues/3182 |
| 989 |
test('Hook subscriptions are properly cleaned up when changing skip back and forth', async () => { |
| 990 |
const pokemonApi = createApi({ |
| 991 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }), |
| 992 |
endpoints: (builder) => ({ |
| 993 |
getPokemonByName: builder.query({ |
| 994 |
queryFn: (name: string) => ({ data: null }), |
| 995 |
keepUnusedDataFor: 1, |
| 996 |
}), |
| 997 |
}), |
| 998 |
}) |
| 999 |
|
| 1000 |
const storeRef = setupApiStore(pokemonApi, undefined, { |
| 1001 |
withoutTestLifecycles: true, |
| 1002 |
}) |
| 1003 |
|
| 1004 |
const checkNumSubscriptions = (arg: string, count: number) => { |
| 1005 |
const subscriptions = getSubscriptions() |
| 1006 |
const cacheKeyEntry = subscriptions[arg] |
| 1007 |
|
| 1008 |
if (cacheKeyEntry) { |
| 1009 |
const subscriptionCount = Object.keys(cacheKeyEntry) //getSubscriptionCount(arg) |
| 1010 |
expect(subscriptionCount).toBe(count) |
| 1011 |
} |
| 1012 |
} |
| 1013 |
|
| 1014 |
// 1) Initial state: an active subscription |
| 1015 |
const { rerender, unmount } = renderHook( |
| 1016 |
([arg, options]: Parameters< |
| 1017 |
typeof pokemonApi.useGetPokemonByNameQuery |
| 1018 |
>) => pokemonApi.useGetPokemonByNameQuery(arg, options), |
| 1019 |
{ |
| 1020 |
wrapper: storeRef.wrapper, |
| 1021 |
initialProps: ['a'], |
| 1022 |
}, |
| 1023 |
) |
| 1024 |
|
| 1025 |
await act(async () => { |
| 1026 |
await waitMs(1) |
| 1027 |
}) |
| 1028 |
|
| 1029 |
// 2) Set the current subscription to `{skip: true} |
| 1030 |
rerender(['a', { skip: true }]) |
| 1031 |
|
| 1032 |
// 3) Change _both_ the cache key _and_ `{skip: false}` at the same time. |
| 1033 |
// This causes the `subscriptionRemoved` check to be `true`. |
| 1034 |
rerender(['b']) |
| 1035 |
|
| 1036 |
// There should only be one active subscription after changing the arg |
| 1037 |
checkNumSubscriptions('b', 1) |
| 1038 |
|
| 1039 |
// 4) Re-render with the same arg. |
| 1040 |
// This causes the `subscriptionRemoved` check to be `false`. |
| 1041 |
// Correct behavior is this does _not_ clear the promise ref, |
| 1042 |
// so |
| 1043 |
rerender(['b']) |
| 1044 |
|
| 1045 |
// There should only be one active subscription after changing the arg |
| 1046 |
checkNumSubscriptions('b', 1) |
| 1047 |
|
| 1048 |
await act(async () => { |
| 1049 |
await waitMs(1) |
| 1050 |
}) |
| 1051 |
|
| 1052 |
unmount() |
| 1053 |
|
| 1054 |
await act(async () => { |
| 1055 |
await waitMs(1) |
| 1056 |
}) |
| 1057 |
|
| 1058 |
// There should be no subscription entries left over after changing |
| 1059 |
// cache key args and swapping `skip` on and off |
| 1060 |
checkNumSubscriptions('b', 0) |
| 1061 |
|
| 1062 |
const finalSubscriptions = getSubscriptions() |
| 1063 |
|
| 1064 |
for (const cacheKeyEntry of Object.values(finalSubscriptions)) { |
| 1065 |
expect(Object.values(cacheKeyEntry!).length).toBe(0) |
| 1066 |
} |
| 1067 |
}) |
| 1068 |
|
| 1069 |
test('Hook subscription failures do not reset isLoading state', async () => { |
| 1070 |
const states: boolean[] = [] |
| 1071 |
|
| 1072 |
function Parent() { |
| 1073 |
const { isLoading } = api.endpoints.getUserAndForceError.useQuery(1) |
| 1074 |
|
| 1075 |
// Collect loading states to verify that it does not revert back to true. |
| 1076 |
states.push(isLoading) |
| 1077 |
|
| 1078 |
// Parent conditionally renders child when loading. |
| 1079 |
if (isLoading) return null |
| 1080 |
|
| 1081 |
return <Child /> |
| 1082 |
} |
| 1083 |
|
| 1084 |
function Child() { |
| 1085 |
// Using the same args as the parent |
| 1086 |
api.endpoints.getUserAndForceError.useQuery(1) |
| 1087 |
|
| 1088 |
return null |
| 1089 |
} |
| 1090 |
|
| 1091 |
render(<Parent />, { wrapper: storeRef.wrapper }) |
| 1092 |
|
| 1093 |
expect(states).toHaveLength(2) |
| 1094 |
|
| 1095 |
// Allow at least three state effects to hit. |
| 1096 |
// Trying to see if any [true, false, true] occurs. |
| 1097 |
await act(async () => { |
| 1098 |
await waitForFakeTimer(150) |
| 1099 |
}) |
| 1100 |
|
| 1101 |
expect(states).toHaveLength(4) |
| 1102 |
|
| 1103 |
await act(async () => { |
| 1104 |
await waitForFakeTimer(150) |
| 1105 |
}) |
| 1106 |
|
| 1107 |
expect(states).toHaveLength(5) |
| 1108 |
|
| 1109 |
await act(async () => { |
| 1110 |
await waitForFakeTimer(150) |
| 1111 |
}) |
| 1112 |
|
| 1113 |
expect(states).toHaveLength(5) |
| 1114 |
|
| 1115 |
// Find if at any time the isLoading state has reverted |
| 1116 |
// E.G.: `[..., true, false, ..., true]` |
| 1117 |
// ^^^^ ^^^^^ ^^^^ |
| 1118 |
const firstTrue = states.indexOf(true) |
| 1119 |
const firstFalse = states.slice(firstTrue).indexOf(false) |
| 1120 |
const revertedState = states.slice(firstFalse).indexOf(true) |
| 1121 |
|
| 1122 |
expect( |
| 1123 |
revertedState, |
| 1124 |
`Expected isLoading state to never revert back to true but did after ${revertedState} renders...`, |
| 1125 |
).toBe(-1) |
| 1126 |
}) |
| 1127 |
|
| 1128 |
describe('Hook middleware requirements', () => { |
| 1129 |
const consoleErrorSpy = vi |
| 1130 |
.spyOn(console, 'error') |
| 1131 |
.mockImplementation(noop) |
| 1132 |
|
| 1133 |
afterEach(() => { |
| 1134 |
consoleErrorSpy.mockClear() |
| 1135 |
}) |
| 1136 |
|
| 1137 |
afterAll(() => { |
| 1138 |
consoleErrorSpy.mockRestore() |
| 1139 |
}) |
| 1140 |
|
| 1141 |
test('Throws error if middleware is not added to the store', async () => { |
| 1142 |
const store = configureStore({ |
| 1143 |
reducer: { |
| 1144 |
[api.reducerPath]: api.reducer, |
| 1145 |
}, |
| 1146 |
}) |
| 1147 |
|
| 1148 |
const doRender = () => { |
| 1149 |
renderHook(() => api.endpoints.getIncrementedAmount.useQuery(), { |
| 1150 |
wrapper: withProvider(store), |
| 1151 |
}) |
| 1152 |
} |
| 1153 |
|
| 1154 |
expect(doRender).toThrowError( |
| 1155 |
/Warning: Middleware for RTK-Query API at reducerPath "api" has not been added to the store/, |
| 1156 |
) |
| 1157 |
}) |
| 1158 |
}) |
| 1159 |
}) |
| 1160 |
|
| 1161 |
describe('useLazyQuery', () => { |
| 1162 |
let data: any |
| 1163 |
|
| 1164 |
afterEach(() => { |
| 1165 |
data = undefined |
| 1166 |
}) |
| 1167 |
|
| 1168 |
let getRenderCount: () => number = () => 0 |
| 1169 |
test('useLazyQuery does not automatically fetch when mounted and has undefined data', async () => { |
| 1170 |
function User() { |
| 1171 |
const [fetchUser, { data: hookData, isFetching, isUninitialized }] = |
| 1172 |
api.endpoints.getUser.useLazyQuery() |
| 1173 |
getRenderCount = useRenderCounter() |
| 1174 |
|
| 1175 |
data = hookData |
| 1176 |
|
| 1177 |
return ( |
| 1178 |
<div> |
| 1179 |
<div data-testid="isUninitialized">{String(isUninitialized)}</div> |
| 1180 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 1181 |
<button data-testid="fetchButton" onClick={() => fetchUser(1)}> |
| 1182 |
fetchUser |
| 1183 |
</button> |
| 1184 |
</div> |
| 1185 |
) |
| 1186 |
} |
| 1187 |
|
| 1188 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 1189 |
expect(getRenderCount()).toBe(1) |
| 1190 |
|
| 1191 |
await waitFor(() => |
| 1192 |
expect(screen.getByTestId('isUninitialized').textContent).toBe('true'), |
| 1193 |
) |
| 1194 |
await waitFor(() => expect(data).toBeUndefined()) |
| 1195 |
|
| 1196 |
fireEvent.click(screen.getByTestId('fetchButton')) |
| 1197 |
expect(getRenderCount()).toBe(2) |
| 1198 |
|
| 1199 |
await waitFor(() => |
| 1200 |
expect(screen.getByTestId('isUninitialized').textContent).toBe('false'), |
| 1201 |
) |
| 1202 |
await waitFor(() => |
| 1203 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 1204 |
) |
| 1205 |
expect(getRenderCount()).toBe(3) |
| 1206 |
|
| 1207 |
fireEvent.click(screen.getByTestId('fetchButton')) |
| 1208 |
await waitFor(() => |
| 1209 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 1210 |
) |
| 1211 |
await waitFor(() => |
| 1212 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 1213 |
) |
| 1214 |
expect(getRenderCount()).toBe(5) |
| 1215 |
}) |
| 1216 |
|
| 1217 |
test('useLazyQuery accepts updated subscription options and only dispatches updateSubscriptionOptions when values are updated', async () => { |
| 1218 |
let interval = 1000 |
| 1219 |
function User() { |
| 1220 |
const [options, setOptions] = useState<SubscriptionOptions>() |
| 1221 |
const [fetchUser, { data: hookData, isFetching, isUninitialized }] = |
| 1222 |
api.endpoints.getUser.useLazyQuery(options) |
| 1223 |
getRenderCount = useRenderCounter() |
| 1224 |
|
| 1225 |
data = hookData |
| 1226 |
|
| 1227 |
return ( |
| 1228 |
<div> |
| 1229 |
<div data-testid="isUninitialized">{String(isUninitialized)}</div> |
| 1230 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 1231 |
|
| 1232 |
<button data-testid="fetchButton" onClick={() => fetchUser(1)}> |
| 1233 |
fetchUser |
| 1234 |
</button> |
| 1235 |
<button |
| 1236 |
data-testid="updateOptions" |
| 1237 |
onClick={() => |
| 1238 |
setOptions({ |
| 1239 |
pollingInterval: interval, |
| 1240 |
}) |
| 1241 |
} |
| 1242 |
> |
| 1243 |
updateOptions |
| 1244 |
</button> |
| 1245 |
</div> |
| 1246 |
) |
| 1247 |
} |
| 1248 |
|
| 1249 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 1250 |
expect(getRenderCount()).toBe(1) // hook mount |
| 1251 |
|
| 1252 |
await waitFor(() => |
| 1253 |
expect(screen.getByTestId('isUninitialized').textContent).toBe('true'), |
| 1254 |
) |
| 1255 |
await waitFor(() => expect(data).toBeUndefined()) |
| 1256 |
|
| 1257 |
fireEvent.click(screen.getByTestId('fetchButton')) |
| 1258 |
expect(getRenderCount()).toBe(2) |
| 1259 |
|
| 1260 |
await waitFor(() => |
| 1261 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 1262 |
) |
| 1263 |
await waitFor(() => |
| 1264 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 1265 |
) |
| 1266 |
expect(getRenderCount()).toBe(3) |
| 1267 |
|
| 1268 |
fireEvent.click(screen.getByTestId('updateOptions')) // setState = 1 |
| 1269 |
expect(getRenderCount()).toBe(4) |
| 1270 |
|
| 1271 |
fireEvent.click(screen.getByTestId('fetchButton')) // perform new request = 2 |
| 1272 |
await waitFor(() => |
| 1273 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 1274 |
) |
| 1275 |
await waitFor(() => |
| 1276 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 1277 |
) |
| 1278 |
expect(getRenderCount()).toBe(6) |
| 1279 |
|
| 1280 |
interval = 1000 |
| 1281 |
|
| 1282 |
fireEvent.click(screen.getByTestId('updateOptions')) // setState = 1 |
| 1283 |
expect(getRenderCount()).toBe(7) |
| 1284 |
|
| 1285 |
fireEvent.click(screen.getByTestId('fetchButton')) |
| 1286 |
await waitFor(() => |
| 1287 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 1288 |
) |
| 1289 |
await waitFor(() => |
| 1290 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 1291 |
) |
| 1292 |
expect(getRenderCount()).toBe(9) |
| 1293 |
|
| 1294 |
expect( |
| 1295 |
actions.filter(api.internalActions.updateSubscriptionOptions.match), |
| 1296 |
).toHaveLength(1) |
| 1297 |
}) |
| 1298 |
|
| 1299 |
test('useLazyQuery accepts updated args and unsubscribes the original query', async () => { |
| 1300 |
function User() { |
| 1301 |
const [fetchUser, { data: hookData, isFetching, isUninitialized }] = |
| 1302 |
api.endpoints.getUser.useLazyQuery() |
| 1303 |
|
| 1304 |
data = hookData |
| 1305 |
|
| 1306 |
return ( |
| 1307 |
<div> |
| 1308 |
<div data-testid="isUninitialized">{String(isUninitialized)}</div> |
| 1309 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 1310 |
|
| 1311 |
<button data-testid="fetchUser1" onClick={() => fetchUser(1)}> |
| 1312 |
fetchUser1 |
| 1313 |
</button> |
| 1314 |
<button data-testid="fetchUser2" onClick={() => fetchUser(2)}> |
| 1315 |
fetchUser2 |
| 1316 |
</button> |
| 1317 |
</div> |
| 1318 |
) |
| 1319 |
} |
| 1320 |
|
| 1321 |
const { unmount } = render(<User />, { wrapper: storeRef.wrapper }) |
| 1322 |
|
| 1323 |
await waitFor(() => |
| 1324 |
expect(screen.getByTestId('isUninitialized').textContent).toBe('true'), |
| 1325 |
) |
| 1326 |
await waitFor(() => expect(data).toBeUndefined()) |
| 1327 |
|
| 1328 |
fireEvent.click(screen.getByTestId('fetchUser1')) |
| 1329 |
|
| 1330 |
await waitFor(() => |
| 1331 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 1332 |
) |
| 1333 |
await waitFor(() => |
| 1334 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 1335 |
) |
| 1336 |
|
| 1337 |
// Being that there is only the initial query, no unsubscribe should be dispatched |
| 1338 |
expect( |
| 1339 |
actions.filter(api.internalActions.unsubscribeQueryResult.match), |
| 1340 |
).toHaveLength(0) |
| 1341 |
|
| 1342 |
fireEvent.click(screen.getByTestId('fetchUser2')) |
| 1343 |
|
| 1344 |
await waitFor(() => |
| 1345 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 1346 |
) |
| 1347 |
await waitFor(() => |
| 1348 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 1349 |
) |
| 1350 |
|
| 1351 |
expect( |
| 1352 |
actions.filter(api.internalActions.unsubscribeQueryResult.match), |
| 1353 |
).toHaveLength(1) |
| 1354 |
|
| 1355 |
fireEvent.click(screen.getByTestId('fetchUser1')) |
| 1356 |
|
| 1357 |
expect( |
| 1358 |
actions.filter(api.internalActions.unsubscribeQueryResult.match), |
| 1359 |
).toHaveLength(2) |
| 1360 |
|
| 1361 |
// we always unsubscribe the original promise and create a new one |
| 1362 |
fireEvent.click(screen.getByTestId('fetchUser1')) |
| 1363 |
expect( |
| 1364 |
actions.filter(api.internalActions.unsubscribeQueryResult.match), |
| 1365 |
).toHaveLength(3) |
| 1366 |
|
| 1367 |
unmount() |
| 1368 |
|
| 1369 |
// We unsubscribe after the component unmounts |
| 1370 |
expect( |
| 1371 |
actions.filter(api.internalActions.unsubscribeQueryResult.match), |
| 1372 |
).toHaveLength(4) |
| 1373 |
}) |
| 1374 |
|
| 1375 |
test('useLazyQuery hook callback returns various properties to handle the result', async () => { |
| 1376 |
const user = userEvent.setup() |
| 1377 |
|
| 1378 |
function User() { |
| 1379 |
const [getUser] = api.endpoints.getUser.useLazyQuery() |
| 1380 |
const [{ successMsg, errMsg, isAborted }, setValues] = useState({ |
| 1381 |
successMsg: '', |
| 1382 |
errMsg: '', |
| 1383 |
isAborted: false, |
| 1384 |
}) |
| 1385 |
|
| 1386 |
const handleClick = (abort: boolean) => async () => { |
| 1387 |
const res = getUser(1) |
| 1388 |
|
| 1389 |
// abort the query immediately to force an error |
| 1390 |
if (abort) res.abort() |
| 1391 |
res |
| 1392 |
.unwrap() |
| 1393 |
.then((result) => { |
| 1394 |
setValues({ |
| 1395 |
successMsg: `Successfully fetched user ${result.name}`, |
| 1396 |
errMsg: '', |
| 1397 |
isAborted: false, |
| 1398 |
}) |
| 1399 |
}) |
| 1400 |
.catch((err) => { |
| 1401 |
setValues({ |
| 1402 |
successMsg: '', |
| 1403 |
errMsg: `An error has occurred fetching userId: ${res.arg}`, |
| 1404 |
isAborted: err.name === 'AbortError', |
| 1405 |
}) |
| 1406 |
}) |
| 1407 |
} |
| 1408 |
|
| 1409 |
return ( |
| 1410 |
<div> |
| 1411 |
<button onClick={handleClick(false)}> |
| 1412 |
Fetch User successfully |
| 1413 |
</button> |
| 1414 |
<button onClick={handleClick(true)}>Fetch User and abort</button> |
| 1415 |
<div>{successMsg}</div> |
| 1416 |
<div>{errMsg}</div> |
| 1417 |
<div>{isAborted ? 'Request was aborted' : ''}</div> |
| 1418 |
</div> |
| 1419 |
) |
| 1420 |
} |
| 1421 |
|
| 1422 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 1423 |
expect(screen.queryByText(/An error has occurred/i)).toBeNull() |
| 1424 |
expect(screen.queryByText(/Successfully fetched user/i)).toBeNull() |
| 1425 |
expect(screen.queryByText('Request was aborted')).toBeNull() |
| 1426 |
|
| 1427 |
fireEvent.click( |
| 1428 |
screen.getByRole('button', { name: 'Fetch User and abort' }), |
| 1429 |
) |
| 1430 |
await screen.findByText('An error has occurred fetching userId: 1') |
| 1431 |
expect(screen.queryByText(/Successfully fetched user/i)).toBeNull() |
| 1432 |
screen.getByText('Request was aborted') |
| 1433 |
|
| 1434 |
await user.click( |
| 1435 |
screen.getByRole('button', { name: 'Fetch User successfully' }), |
| 1436 |
) |
| 1437 |
|
| 1438 |
await screen.findByText('Successfully fetched user Timmy') |
| 1439 |
expect(screen.queryByText(/An error has occurred/i)).toBeNull() |
| 1440 |
expect(screen.queryByText('Request was aborted')).toBeNull() |
| 1441 |
}) |
| 1442 |
|
| 1443 |
test('unwrapping the useLazyQuery trigger result does not throw on ConditionError and instead returns the aggregate error', async () => { |
| 1444 |
function User() { |
| 1445 |
const [getUser, { data, error }] = |
| 1446 |
api.endpoints.getUserAndForceError.useLazyQuery() |
| 1447 |
|
| 1448 |
const [unwrappedError, setUnwrappedError] = useState<any>() |
| 1449 |
|
| 1450 |
const handleClick = async () => { |
| 1451 |
const res = getUser(1) |
| 1452 |
|
| 1453 |
try { |
| 1454 |
await res.unwrap() |
| 1455 |
} catch (error) { |
| 1456 |
setUnwrappedError(error) |
| 1457 |
} |
| 1458 |
} |
| 1459 |
|
| 1460 |
return ( |
| 1461 |
<div> |
| 1462 |
<button onClick={handleClick}>Fetch User</button> |
| 1463 |
<div data-testid="result">{JSON.stringify(data)}</div> |
| 1464 |
<div data-testid="error">{JSON.stringify(error)}</div> |
| 1465 |
<div data-testid="unwrappedError"> |
| 1466 |
{JSON.stringify(unwrappedError)} |
| 1467 |
</div> |
| 1468 |
</div> |
| 1469 |
) |
| 1470 |
} |
| 1471 |
|
| 1472 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 1473 |
|
| 1474 |
const fetchButton = screen.getByRole('button', { name: 'Fetch User' }) |
| 1475 |
fireEvent.click(fetchButton) |
| 1476 |
fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real error to resolve. |
| 1477 |
|
| 1478 |
await waitFor(() => { |
| 1479 |
const errorResult = screen.getByTestId('error')?.textContent |
| 1480 |
const unwrappedErrorResult = |
| 1481 |
screen.getByTestId('unwrappedError')?.textContent |
| 1482 |
|
| 1483 |
if (errorResult && unwrappedErrorResult) { |
| 1484 |
expect(JSON.parse(errorResult)).toMatchObject({ |
| 1485 |
status: 500, |
| 1486 |
data: null, |
| 1487 |
}) |
| 1488 |
expect(JSON.parse(unwrappedErrorResult)).toMatchObject( |
| 1489 |
JSON.parse(errorResult), |
| 1490 |
) |
| 1491 |
} |
| 1492 |
}) |
| 1493 |
|
| 1494 |
expect(screen.getByTestId('result').textContent).toBe('') |
| 1495 |
}) |
| 1496 |
|
| 1497 |
test('useLazyQuery does not throw on ConditionError and instead returns the aggregate result', async () => { |
| 1498 |
function User() { |
| 1499 |
const [getUser, { data, error }] = api.endpoints.getUser.useLazyQuery() |
| 1500 |
|
| 1501 |
const [unwrappedResult, setUnwrappedResult] = useState< |
| 1502 |
undefined | { name: string } |
| 1503 |
>() |
| 1504 |
|
| 1505 |
const handleClick = async () => { |
| 1506 |
const res = getUser(1) |
| 1507 |
|
| 1508 |
const result = await res.unwrap() |
| 1509 |
setUnwrappedResult(result) |
| 1510 |
} |
| 1511 |
|
| 1512 |
return ( |
| 1513 |
<div> |
| 1514 |
<button onClick={handleClick}>Fetch User</button> |
| 1515 |
<div data-testid="result">{JSON.stringify(data)}</div> |
| 1516 |
<div data-testid="error">{JSON.stringify(error)}</div> |
| 1517 |
<div data-testid="unwrappedResult"> |
| 1518 |
{JSON.stringify(unwrappedResult)} |
| 1519 |
</div> |
| 1520 |
</div> |
| 1521 |
) |
| 1522 |
} |
| 1523 |
|
| 1524 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 1525 |
|
| 1526 |
const fetchButton = screen.getByRole('button', { name: 'Fetch User' }) |
| 1527 |
fireEvent.click(fetchButton) |
| 1528 |
fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real result to resolve and ignore the error. |
| 1529 |
|
| 1530 |
await waitFor(() => { |
| 1531 |
const dataResult = screen.getByTestId('error')?.textContent |
| 1532 |
const unwrappedDataResult = |
| 1533 |
screen.getByTestId('unwrappedResult')?.textContent |
| 1534 |
|
| 1535 |
if (dataResult && unwrappedDataResult) { |
| 1536 |
expect(JSON.parse(dataResult)).toMatchObject({ |
| 1537 |
name: 'Timmy', |
| 1538 |
}) |
| 1539 |
expect(JSON.parse(unwrappedDataResult)).toMatchObject( |
| 1540 |
JSON.parse(dataResult), |
| 1541 |
) |
| 1542 |
} |
| 1543 |
}) |
| 1544 |
|
| 1545 |
expect(screen.getByTestId('error').textContent).toBe('') |
| 1546 |
}) |
| 1547 |
|
| 1548 |
test('useLazyQuery trigger promise returns the correctly updated data', async () => { |
| 1549 |
const user = userEvent.setup() |
| 1550 |
|
| 1551 |
const LazyUnwrapUseEffect = () => { |
| 1552 |
const [triggerGetIncrementedAmount, { isFetching, isSuccess, data }] = |
| 1553 |
api.endpoints.getIncrementedAmount.useLazyQuery() |
| 1554 |
|
| 1555 |
type AmountData = { amount: number } | undefined |
| 1556 |
|
| 1557 |
const [triggerUpdate] = api.endpoints.triggerUpdatedAmount.useMutation() |
| 1558 |
|
| 1559 |
const [dataFromQuery, setDataFromQuery] = |
| 1560 |
useState<AmountData>(undefined) |
| 1561 |
const [dataFromTrigger, setDataFromTrigger] = |
| 1562 |
useState<AmountData>(undefined) |
| 1563 |
|
| 1564 |
const handleLoad = async () => { |
| 1565 |
try { |
| 1566 |
const res = await triggerGetIncrementedAmount().unwrap() |
| 1567 |
|
| 1568 |
setDataFromTrigger(res) // adding client side state here will cause stale data |
| 1569 |
} catch (error) { |
| 1570 |
console.error('Error handling increment trigger', error) |
| 1571 |
} |
| 1572 |
} |
| 1573 |
|
| 1574 |
const handleMutate = async () => { |
| 1575 |
try { |
| 1576 |
await triggerUpdate() |
| 1577 |
// Force the lazy trigger to refetch |
| 1578 |
await handleLoad() |
| 1579 |
} catch (error) { |
| 1580 |
console.error('Error handling mutate trigger', error) |
| 1581 |
} |
| 1582 |
} |
| 1583 |
|
| 1584 |
useEffect(() => { |
| 1585 |
// Intentionally copy to local state for comparison purposes |
| 1586 |
setDataFromQuery(data) |
| 1587 |
}, [data]) |
| 1588 |
|
| 1589 |
let content: React.ReactNode | null = null |
| 1590 |
|
| 1591 |
if (isFetching) { |
| 1592 |
content = <div className="loading">Loading</div> |
| 1593 |
} else if (isSuccess) { |
| 1594 |
content = ( |
| 1595 |
<div className="wrapper"> |
| 1596 |
<div> |
| 1597 |
useEffect data: {dataFromQuery?.amount ?? 'No query amount'} |
| 1598 |
</div> |
| 1599 |
<div> |
| 1600 |
Unwrap data: {dataFromTrigger?.amount ?? 'No trigger amount'} |
| 1601 |
</div> |
| 1602 |
</div> |
| 1603 |
) |
| 1604 |
} |
| 1605 |
|
| 1606 |
return ( |
| 1607 |
<div className="outer"> |
| 1608 |
<button onClick={() => handleLoad()}>Load Data</button> |
| 1609 |
<button onClick={() => handleMutate()}>Update Data</button> |
| 1610 |
{content} |
| 1611 |
</div> |
| 1612 |
) |
| 1613 |
} |
| 1614 |
|
| 1615 |
render(<LazyUnwrapUseEffect />, { wrapper: storeRef.wrapper }) |
| 1616 |
|
| 1617 |
// Kick off the initial fetch via lazy query trigger |
| 1618 |
await user.click(screen.getByText('Load Data')) |
| 1619 |
|
| 1620 |
// We get back initial data, which should get copied into local state, |
| 1621 |
// and also should come back as valid via the lazy trigger promise |
| 1622 |
await waitFor(() => { |
| 1623 |
expect(screen.getByText('useEffect data: 1')).toBeTruthy() |
| 1624 |
expect(screen.getByText('Unwrap data: 1')).toBeTruthy() |
| 1625 |
}) |
| 1626 |
|
| 1627 |
// If we mutate and then re-run the lazy trigger afterwards... |
| 1628 |
await user.click(screen.getByText('Update Data')) |
| 1629 |
|
| 1630 |
// We should see both sets of data agree (ie, the lazy trigger promise |
| 1631 |
// should not return stale data or be out of sync with the hook). |
| 1632 |
// Prior to PR #4651, this would fail because the trigger never updated properly. |
| 1633 |
await waitFor(() => { |
| 1634 |
expect(screen.getByText('useEffect data: 2')).toBeTruthy() |
| 1635 |
expect(screen.getByText('Unwrap data: 2')).toBeTruthy() |
| 1636 |
}) |
| 1637 |
}) |
| 1638 |
|
| 1639 |
test('`reset` sets state back to original state', async () => { |
| 1640 |
const user = userEvent.setup() |
| 1641 |
|
| 1642 |
function User() { |
| 1643 |
const [getUser, { isSuccess, isUninitialized, reset }, _lastInfo] = |
| 1644 |
api.endpoints.getUser.useLazyQuery() |
| 1645 |
|
| 1646 |
const handleFetchClick = async () => { |
| 1647 |
await getUser(1).unwrap() |
| 1648 |
} |
| 1649 |
|
| 1650 |
return ( |
| 1651 |
<div> |
| 1652 |
<span> |
| 1653 |
{isUninitialized |
| 1654 |
? 'isUninitialized' |
| 1655 |
: isSuccess |
| 1656 |
? 'isSuccess' |
| 1657 |
: 'other'} |
| 1658 |
</span> |
| 1659 |
<button onClick={handleFetchClick}>Fetch User</button> |
| 1660 |
<button onClick={reset}>Reset</button> |
| 1661 |
</div> |
| 1662 |
) |
| 1663 |
} |
| 1664 |
|
| 1665 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 1666 |
|
| 1667 |
await screen.findByText(/isUninitialized/i) |
| 1668 |
expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(0) |
| 1669 |
|
| 1670 |
await user.click(screen.getByRole('button', { name: 'Fetch User' })) |
| 1671 |
|
| 1672 |
await screen.findByText(/isSuccess/i) |
| 1673 |
expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(1) |
| 1674 |
|
| 1675 |
await user.click( |
| 1676 |
screen.getByRole('button', { |
| 1677 |
name: 'Reset', |
| 1678 |
}), |
| 1679 |
) |
| 1680 |
|
| 1681 |
await screen.findByText(/isUninitialized/i) |
| 1682 |
expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(0) |
| 1683 |
}) |
| 1684 |
}) |
| 1685 |
|
| 1686 |
describe('useInfiniteQuery', () => { |
| 1687 |
type Pokemon = { |
| 1688 |
id: string |
| 1689 |
name: string |
| 1690 |
} |
| 1691 |
|
| 1692 |
const pokemonApi = createApi({ |
| 1693 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }), |
| 1694 |
endpoints: (builder) => ({ |
| 1695 |
getInfinitePokemon: builder.infiniteQuery<Pokemon, string, number>({ |
| 1696 |
infiniteQueryOptions: { |
| 1697 |
initialPageParam: 0, |
| 1698 |
getNextPageParam: ( |
| 1699 |
lastPage, |
| 1700 |
allPages, |
| 1701 |
lastPageParam, |
| 1702 |
allPageParams, |
| 1703 |
) => lastPageParam + 1, |
| 1704 |
getPreviousPageParam: ( |
| 1705 |
firstPage, |
| 1706 |
allPages, |
| 1707 |
firstPageParam, |
| 1708 |
allPageParams, |
| 1709 |
) => { |
| 1710 |
return firstPageParam > 0 ? firstPageParam - 1 : undefined |
| 1711 |
}, |
| 1712 |
}, |
| 1713 |
query({ pageParam }) { |
| 1714 |
return `https://example.com/listItems?page=${pageParam}` |
| 1715 |
}, |
| 1716 |
}), |
| 1717 |
}), |
| 1718 |
}) |
| 1719 |
|
| 1720 |
const pokemonApiWithRefetch = createApi({ |
| 1721 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }), |
| 1722 |
endpoints: (builder) => ({ |
| 1723 |
getInfinitePokemon: builder.infiniteQuery<Pokemon, string, number>({ |
| 1724 |
infiniteQueryOptions: { |
| 1725 |
initialPageParam: 0, |
| 1726 |
getNextPageParam: ( |
| 1727 |
lastPage, |
| 1728 |
allPages, |
| 1729 |
lastPageParam, |
| 1730 |
allPageParams, |
| 1731 |
) => lastPageParam + 1, |
| 1732 |
getPreviousPageParam: ( |
| 1733 |
firstPage, |
| 1734 |
allPages, |
| 1735 |
firstPageParam, |
| 1736 |
allPageParams, |
| 1737 |
) => { |
| 1738 |
return firstPageParam > 0 ? firstPageParam - 1 : undefined |
| 1739 |
}, |
| 1740 |
}, |
| 1741 |
query({ pageParam }) { |
| 1742 |
return `https://example.com/listItems?page=${pageParam}` |
| 1743 |
}, |
| 1744 |
}), |
| 1745 |
}), |
| 1746 |
refetchOnMountOrArgChange: true, |
| 1747 |
}) |
| 1748 |
|
| 1749 |
function PokemonList({ |
| 1750 |
api, |
| 1751 |
arg = 'fire', |
| 1752 |
initialPageParam = 0, |
| 1753 |
}: { |
| 1754 |
api: typeof pokemonApi |
| 1755 |
arg?: string |
| 1756 |
initialPageParam?: number |
| 1757 |
}) { |
| 1758 |
const { |
| 1759 |
data, |
| 1760 |
isFetching, |
| 1761 |
isUninitialized, |
| 1762 |
fetchNextPage, |
| 1763 |
fetchPreviousPage, |
| 1764 |
refetch, |
| 1765 |
} = api.useGetInfinitePokemonInfiniteQuery(arg, { |
| 1766 |
initialPageParam, |
| 1767 |
}) |
| 1768 |
|
| 1769 |
const handlePreviousPage = async () => { |
| 1770 |
const res = await fetchPreviousPage() |
| 1771 |
} |
| 1772 |
|
| 1773 |
const handleNextPage = async () => { |
| 1774 |
const res = await fetchNextPage() |
| 1775 |
} |
| 1776 |
|
| 1777 |
const handleRefetch = async () => { |
| 1778 |
const res = await refetch() |
| 1779 |
} |
| 1780 |
|
| 1781 |
return ( |
| 1782 |
<div> |
| 1783 |
<div data-testid="isUninitialized">{String(isUninitialized)}</div> |
| 1784 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 1785 |
<div>Type: {arg}</div> |
| 1786 |
<div data-testid="data"> |
| 1787 |
{data?.pages.map((page, i: number | null | undefined) => ( |
| 1788 |
<div key={i}>{page.name}</div> |
| 1789 |
))} |
| 1790 |
</div> |
| 1791 |
<button data-testid="prevPage" onClick={() => handlePreviousPage()}> |
| 1792 |
previousPage |
| 1793 |
</button> |
| 1794 |
<button data-testid="nextPage" onClick={() => handleNextPage()}> |
| 1795 |
nextPage |
| 1796 |
</button> |
| 1797 |
<button data-testid="refetch" onClick={() => handleRefetch()}> |
| 1798 |
refetch |
| 1799 |
</button> |
| 1800 |
</div> |
| 1801 |
) |
| 1802 |
} |
| 1803 |
|
| 1804 |
beforeEach(() => { |
| 1805 |
server.use( |
| 1806 |
http.get('https://example.com/listItems', ({ request }) => { |
| 1807 |
const url = new URL(request.url) |
| 1808 |
const pageString = url.searchParams.get('page') |
| 1809 |
const pageNum = parseInt(pageString || '0') |
| 1810 |
|
| 1811 |
const results: Pokemon = { |
| 1812 |
id: `${pageNum}`, |
| 1813 |
name: `Pokemon ${pageNum}`, |
| 1814 |
} |
| 1815 |
|
| 1816 |
return HttpResponse.json(results) |
| 1817 |
}), |
| 1818 |
) |
| 1819 |
}) |
| 1820 |
|
| 1821 |
test.each([ |
| 1822 |
['no refetch', pokemonApi], |
| 1823 |
['with refetch', pokemonApiWithRefetch], |
| 1824 |
])(`useInfiniteQuery %s`, async (_, pokemonApi) => { |
| 1825 |
const storeRef = setupApiStore(pokemonApi, undefined, { |
| 1826 |
withoutTestLifecycles: true, |
| 1827 |
}) |
| 1828 |
|
| 1829 |
const { takeRender, render, getCurrentRender } = createRenderStream({ |
| 1830 |
snapshotDOM: true, |
| 1831 |
}) |
| 1832 |
|
| 1833 |
const checkNumQueries = (count: number) => { |
| 1834 |
const cacheEntries = Object.keys(storeRef.store.getState().api.queries) |
| 1835 |
const queries = cacheEntries.length |
| 1836 |
//console.log('queries', queries, storeRef.store.getState().api.queries) |
| 1837 |
|
| 1838 |
expect(queries).toBe(count) |
| 1839 |
} |
| 1840 |
|
| 1841 |
const checkEntryFlags = ( |
| 1842 |
arg: string, |
| 1843 |
expectedFlags: Partial<InfiniteQueryResultFlags>, |
| 1844 |
) => { |
| 1845 |
const selector = pokemonApi.endpoints.getInfinitePokemon.select(arg) |
| 1846 |
const entry = selector(storeRef.store.getState()) |
| 1847 |
|
| 1848 |
const actualFlags: InfiniteQueryResultFlags = { |
| 1849 |
hasNextPage: false, |
| 1850 |
hasPreviousPage: false, |
| 1851 |
isFetchingNextPage: false, |
| 1852 |
isFetchingPreviousPage: false, |
| 1853 |
isFetchNextPageError: false, |
| 1854 |
isFetchPreviousPageError: false, |
| 1855 |
...expectedFlags, |
| 1856 |
} |
| 1857 |
|
| 1858 |
expect(entry).toMatchObject(actualFlags) |
| 1859 |
} |
| 1860 |
|
| 1861 |
const checkPageRows = ( |
| 1862 |
withinDOM: () => SyncScreen, |
| 1863 |
type: string, |
| 1864 |
ids: number[], |
| 1865 |
) => { |
| 1866 |
expect(withinDOM().getByText(`Type: ${type}`)).toBeTruthy() |
| 1867 |
for (const id of ids) { |
| 1868 |
expect(withinDOM().getByText(`Pokemon ${id}`)).toBeTruthy() |
| 1869 |
} |
| 1870 |
} |
| 1871 |
|
| 1872 |
async function waitForFetch(handleExtraMiddleRender = false) { |
| 1873 |
{ |
| 1874 |
const { withinDOM } = await takeRender() |
| 1875 |
expect(withinDOM().getByTestId('isFetching').textContent).toBe('true') |
| 1876 |
} |
| 1877 |
|
| 1878 |
// We seem to do an extra render when fetching an uninitialized entry |
| 1879 |
if (handleExtraMiddleRender) { |
| 1880 |
{ |
| 1881 |
const { withinDOM } = await takeRender() |
| 1882 |
expect(withinDOM().getByTestId('isFetching').textContent).toBe( |
| 1883 |
'true', |
| 1884 |
) |
| 1885 |
} |
| 1886 |
} |
| 1887 |
|
| 1888 |
{ |
| 1889 |
// Second fetch complete |
| 1890 |
const { withinDOM } = await takeRender() |
| 1891 |
expect(withinDOM().getByTestId('isFetching').textContent).toBe( |
| 1892 |
'false', |
| 1893 |
) |
| 1894 |
} |
| 1895 |
} |
| 1896 |
|
| 1897 |
const utils = render(<PokemonList api={pokemonApi} />, { |
| 1898 |
wrapper: storeRef.wrapper, |
| 1899 |
}) |
| 1900 |
checkNumQueries(1) |
| 1901 |
checkEntryFlags('fire', {}) |
| 1902 |
await waitForFetch(true) |
| 1903 |
checkNumQueries(1) |
| 1904 |
checkPageRows(getCurrentRender().withinDOM, 'fire', [0]) |
| 1905 |
checkEntryFlags('fire', { |
| 1906 |
hasNextPage: true, |
| 1907 |
}) |
| 1908 |
|
| 1909 |
fireEvent.click(screen.getByTestId('nextPage'), {}) |
| 1910 |
checkEntryFlags('fire', { |
| 1911 |
hasNextPage: true, |
| 1912 |
isFetchingNextPage: true, |
| 1913 |
}) |
| 1914 |
await waitForFetch() |
| 1915 |
checkPageRows(getCurrentRender().withinDOM, 'fire', [0, 1]) |
| 1916 |
checkEntryFlags('fire', { |
| 1917 |
hasNextPage: true, |
| 1918 |
}) |
| 1919 |
|
| 1920 |
fireEvent.click(screen.getByTestId('nextPage')) |
| 1921 |
await waitForFetch() |
| 1922 |
checkPageRows(getCurrentRender().withinDOM, 'fire', [0, 1, 2]) |
| 1923 |
|
| 1924 |
utils.rerender( |
| 1925 |
<PokemonList api={pokemonApi} arg="water" initialPageParam={3} />, |
| 1926 |
) |
| 1927 |
checkEntryFlags('water', {}) |
| 1928 |
await waitForFetch(true) |
| 1929 |
checkNumQueries(2) |
| 1930 |
checkPageRows(getCurrentRender().withinDOM, 'water', [3]) |
| 1931 |
checkEntryFlags('water', { |
| 1932 |
hasNextPage: true, |
| 1933 |
hasPreviousPage: true, |
| 1934 |
}) |
| 1935 |
|
| 1936 |
fireEvent.click(screen.getByTestId('nextPage')) |
| 1937 |
checkEntryFlags('water', { |
| 1938 |
hasNextPage: true, |
| 1939 |
hasPreviousPage: true, |
| 1940 |
isFetchingNextPage: true, |
| 1941 |
}) |
| 1942 |
await waitForFetch() |
| 1943 |
checkPageRows(getCurrentRender().withinDOM, 'water', [3, 4]) |
| 1944 |
checkEntryFlags('water', { |
| 1945 |
hasNextPage: true, |
| 1946 |
hasPreviousPage: true, |
| 1947 |
}) |
| 1948 |
|
| 1949 |
fireEvent.click(screen.getByTestId('prevPage')) |
| 1950 |
checkEntryFlags('water', { |
| 1951 |
hasNextPage: true, |
| 1952 |
hasPreviousPage: true, |
| 1953 |
isFetchingPreviousPage: true, |
| 1954 |
}) |
| 1955 |
await waitForFetch() |
| 1956 |
checkPageRows(getCurrentRender().withinDOM, 'water', [2, 3, 4]) |
| 1957 |
checkEntryFlags('water', { |
| 1958 |
hasNextPage: true, |
| 1959 |
hasPreviousPage: true, |
| 1960 |
}) |
| 1961 |
|
| 1962 |
fireEvent.click(screen.getByTestId('refetch')) |
| 1963 |
checkEntryFlags('water', { |
| 1964 |
hasNextPage: true, |
| 1965 |
hasPreviousPage: true, |
| 1966 |
}) |
| 1967 |
await waitForFetch() |
| 1968 |
checkPageRows(getCurrentRender().withinDOM, 'water', [2, 3, 4]) |
| 1969 |
checkEntryFlags('water', { |
| 1970 |
hasNextPage: true, |
| 1971 |
hasPreviousPage: true, |
| 1972 |
}) |
| 1973 |
}) |
| 1974 |
|
| 1975 |
test('Object page params does not keep forcing refetching', async () => { |
| 1976 |
type Project = { |
| 1977 |
id: number |
| 1978 |
createdAt: string |
| 1979 |
} |
| 1980 |
|
| 1981 |
type ProjectsResponse = { |
| 1982 |
projects: Project[] |
| 1983 |
numFound: number |
| 1984 |
serverTime: string |
| 1985 |
} |
| 1986 |
|
| 1987 |
interface ProjectsInitialPageParam { |
| 1988 |
offset: number |
| 1989 |
limit: number |
| 1990 |
} |
| 1991 |
|
| 1992 |
const apiWithInfiniteScroll = createApi({ |
| 1993 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }), |
| 1994 |
endpoints: (builder) => ({ |
| 1995 |
projectsLimitOffset: builder.infiniteQuery< |
| 1996 |
ProjectsResponse, |
| 1997 |
void, |
| 1998 |
ProjectsInitialPageParam |
| 1999 |
>({ |
| 2000 |
infiniteQueryOptions: { |
| 2001 |
initialPageParam: { |
| 2002 |
offset: 0, |
| 2003 |
limit: 20, |
| 2004 |
}, |
| 2005 |
getNextPageParam: ( |
| 2006 |
lastPage, |
| 2007 |
allPages, |
| 2008 |
lastPageParam, |
| 2009 |
allPageParams, |
| 2010 |
) => { |
| 2011 |
const nextOffset = lastPageParam.offset + lastPageParam.limit |
| 2012 |
const remainingItems = lastPage?.numFound - nextOffset |
| 2013 |
|
| 2014 |
if (remainingItems <= 0) { |
| 2015 |
return undefined |
| 2016 |
} |
| 2017 |
|
| 2018 |
return { |
| 2019 |
...lastPageParam, |
| 2020 |
offset: nextOffset, |
| 2021 |
} |
| 2022 |
}, |
| 2023 |
getPreviousPageParam: ( |
| 2024 |
firstPage, |
| 2025 |
allPages, |
| 2026 |
firstPageParam, |
| 2027 |
allPageParams, |
| 2028 |
) => { |
| 2029 |
const prevOffset = firstPageParam.offset - firstPageParam.limit |
| 2030 |
if (prevOffset < 0) return undefined |
| 2031 |
|
| 2032 |
return { |
| 2033 |
...firstPageParam, |
| 2034 |
offset: firstPageParam.offset - firstPageParam.limit, |
| 2035 |
} |
| 2036 |
}, |
| 2037 |
}, |
| 2038 |
query: ({ pageParam }) => { |
| 2039 |
const { offset, limit } = pageParam |
| 2040 |
return { |
| 2041 |
url: `https://example.com/api/projectsLimitOffset?offset=${offset}&limit=${limit}`, |
| 2042 |
method: 'GET', |
| 2043 |
} |
| 2044 |
}, |
| 2045 |
}), |
| 2046 |
}), |
| 2047 |
}) |
| 2048 |
|
| 2049 |
const projects = Array.from({ length: 50 }, (_, i) => { |
| 2050 |
return { |
| 2051 |
id: i, |
| 2052 |
createdAt: Date.now() + i * 1000, |
| 2053 |
} |
| 2054 |
}) |
| 2055 |
|
| 2056 |
let numRequests = 0 |
| 2057 |
|
| 2058 |
server.use( |
| 2059 |
http.get( |
| 2060 |
'https://example.com/api/projectsLimitOffset', |
| 2061 |
async ({ request }) => { |
| 2062 |
const url = new URL(request.url) |
| 2063 |
const limit = parseInt(url.searchParams.get('limit') ?? '5', 10) |
| 2064 |
let offset = parseInt(url.searchParams.get('offset') ?? '0', 10) |
| 2065 |
|
| 2066 |
numRequests++ |
| 2067 |
|
| 2068 |
if (isNaN(offset) || offset < 0) { |
| 2069 |
offset = 0 |
| 2070 |
} |
| 2071 |
if (isNaN(limit) || limit <= 0) { |
| 2072 |
return HttpResponse.json( |
| 2073 |
{ |
| 2074 |
message: |
| 2075 |
"Invalid 'limit' parameter. It must be a positive integer.", |
| 2076 |
} as any, |
| 2077 |
{ status: 400 }, |
| 2078 |
) |
| 2079 |
} |
| 2080 |
|
| 2081 |
const result = projects.slice(offset, offset + limit) |
| 2082 |
|
| 2083 |
await delay(10) |
| 2084 |
return HttpResponse.json({ |
| 2085 |
projects: result, |
| 2086 |
serverTime: Date.now(), |
| 2087 |
numFound: projects.length, |
| 2088 |
}) |
| 2089 |
}, |
| 2090 |
), |
| 2091 |
) |
| 2092 |
|
| 2093 |
function LimitOffsetExample() { |
| 2094 |
const { |
| 2095 |
data, |
| 2096 |
hasPreviousPage, |
| 2097 |
hasNextPage, |
| 2098 |
error, |
| 2099 |
isFetching, |
| 2100 |
isLoading, |
| 2101 |
isError, |
| 2102 |
fetchNextPage, |
| 2103 |
fetchPreviousPage, |
| 2104 |
isFetchingNextPage, |
| 2105 |
isFetchingPreviousPage, |
| 2106 |
status, |
| 2107 |
} = apiWithInfiniteScroll.useProjectsLimitOffsetInfiniteQuery( |
| 2108 |
undefined, |
| 2109 |
{ |
| 2110 |
initialPageParam: { |
| 2111 |
offset: 10, |
| 2112 |
limit: 10, |
| 2113 |
}, |
| 2114 |
}, |
| 2115 |
) |
| 2116 |
|
| 2117 |
const [counter, setCounter] = useState(0) |
| 2118 |
|
| 2119 |
const combinedData = useMemo(() => { |
| 2120 |
return data?.pages?.map((item) => item?.projects)?.flat() |
| 2121 |
}, [data]) |
| 2122 |
|
| 2123 |
return ( |
| 2124 |
<div> |
| 2125 |
<h2>Limit and Offset Infinite Scroll</h2> |
| 2126 |
<button onClick={() => setCounter((c) => c + 1)}>Increment</button> |
| 2127 |
<div>Counter: {counter}</div> |
| 2128 |
{isLoading ? ( |
| 2129 |
<p>Loading...</p> |
| 2130 |
) : isError ? ( |
| 2131 |
<span>Error: {error.message}</span> |
| 2132 |
) : null} |
| 2133 |
|
| 2134 |
<> |
| 2135 |
<div> |
| 2136 |
<button |
| 2137 |
onClick={() => fetchPreviousPage()} |
| 2138 |
disabled={!hasPreviousPage || isFetchingPreviousPage} |
| 2139 |
> |
| 2140 |
{isFetchingPreviousPage |
| 2141 |
? 'Loading more...' |
| 2142 |
: hasPreviousPage |
| 2143 |
? 'Load Older' |
| 2144 |
: 'Nothing more to load'} |
| 2145 |
</button> |
| 2146 |
</div> |
| 2147 |
<div data-testid="projects"> |
| 2148 |
{combinedData?.map((project, index, arr) => { |
| 2149 |
return ( |
| 2150 |
<div key={project.id}> |
| 2151 |
<div data-testid="project"> |
| 2152 |
<div>{`Project ${project.id} (created at: ${project.createdAt})`}</div> |
| 2153 |
</div> |
| 2154 |
</div> |
| 2155 |
) |
| 2156 |
})} |
| 2157 |
</div> |
| 2158 |
<div> |
| 2159 |
<button |
| 2160 |
onClick={() => fetchNextPage()} |
| 2161 |
disabled={!hasNextPage || isFetchingNextPage} |
| 2162 |
> |
| 2163 |
{isFetchingNextPage |
| 2164 |
? 'Loading more...' |
| 2165 |
: hasNextPage |
| 2166 |
? 'Load Newer' |
| 2167 |
: 'Nothing more to load'} |
| 2168 |
</button> |
| 2169 |
</div> |
| 2170 |
<div> |
| 2171 |
{isFetching && !isFetchingPreviousPage && !isFetchingNextPage |
| 2172 |
? 'Background Updating...' |
| 2173 |
: null} |
| 2174 |
</div> |
| 2175 |
</> |
| 2176 |
</div> |
| 2177 |
) |
| 2178 |
} |
| 2179 |
|
| 2180 |
const storeRef = setupApiStore( |
| 2181 |
apiWithInfiniteScroll, |
| 2182 |
{ ...actionsReducer }, |
| 2183 |
{ |
| 2184 |
withoutTestLifecycles: true, |
| 2185 |
}, |
| 2186 |
) |
| 2187 |
|
| 2188 |
const { takeRender, render, totalRenderCount } = createRenderStream({ |
| 2189 |
snapshotDOM: true, |
| 2190 |
}) |
| 2191 |
|
| 2192 |
render(<LimitOffsetExample />, { |
| 2193 |
wrapper: storeRef.wrapper, |
| 2194 |
}) |
| 2195 |
|
| 2196 |
{ |
| 2197 |
const { withinDOM } = await takeRender() |
| 2198 |
withinDOM().getByText('Counter: 0') |
| 2199 |
withinDOM().getByText('Loading...') |
| 2200 |
} |
| 2201 |
|
| 2202 |
{ |
| 2203 |
const { withinDOM } = await takeRender() |
| 2204 |
withinDOM().getByText('Counter: 0') |
| 2205 |
withinDOM().getByText('Loading...') |
| 2206 |
} |
| 2207 |
|
| 2208 |
{ |
| 2209 |
const { withinDOM } = await takeRender() |
| 2210 |
withinDOM().getByText('Counter: 0') |
| 2211 |
|
| 2212 |
expect(withinDOM().getAllByTestId('project').length).toBe(10) |
| 2213 |
expect(withinDOM().queryByTestId('Loading...')).toBeNull() |
| 2214 |
} |
| 2215 |
|
| 2216 |
expect(totalRenderCount()).toBe(3) |
| 2217 |
expect(numRequests).toBe(1) |
| 2218 |
}) |
| 2219 |
}) |
| 2220 |
|
| 2221 |
describe('useMutation', () => { |
| 2222 |
test('useMutation hook sets and unsets the isLoading flag when running', async () => { |
| 2223 |
function User() { |
| 2224 |
const [updateUser, { isLoading }] = |
| 2225 |
api.endpoints.updateUser.useMutation() |
| 2226 |
|
| 2227 |
return ( |
| 2228 |
<div> |
| 2229 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 2230 |
<button onClick={() => updateUser({ name: 'Banana' })}> |
| 2231 |
Update User |
| 2232 |
</button> |
| 2233 |
</div> |
| 2234 |
) |
| 2235 |
} |
| 2236 |
|
| 2237 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2238 |
|
| 2239 |
await waitFor(() => |
| 2240 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 2241 |
) |
| 2242 |
fireEvent.click(screen.getByText('Update User')) |
| 2243 |
await waitFor(() => |
| 2244 |
expect(screen.getByTestId('isLoading').textContent).toBe('true'), |
| 2245 |
) |
| 2246 |
await waitFor(() => |
| 2247 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 2248 |
) |
| 2249 |
}) |
| 2250 |
|
| 2251 |
test('useMutation hook sets data to the resolved response on success', async () => { |
| 2252 |
const result = { name: 'Banana' } |
| 2253 |
|
| 2254 |
function User() { |
| 2255 |
const [updateUser, { data }] = api.endpoints.updateUser.useMutation() |
| 2256 |
|
| 2257 |
return ( |
| 2258 |
<div> |
| 2259 |
<div data-testid="result">{JSON.stringify(data)}</div> |
| 2260 |
<button onClick={() => updateUser({ name: 'Banana' })}> |
| 2261 |
Update User |
| 2262 |
</button> |
| 2263 |
</div> |
| 2264 |
) |
| 2265 |
} |
| 2266 |
|
| 2267 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2268 |
|
| 2269 |
fireEvent.click(screen.getByText('Update User')) |
| 2270 |
await waitFor(() => |
| 2271 |
expect(screen.getByTestId('result').textContent).toBe( |
| 2272 |
JSON.stringify(result), |
| 2273 |
), |
| 2274 |
) |
| 2275 |
}) |
| 2276 |
|
| 2277 |
test('useMutation hook callback returns various properties to handle the result', async () => { |
| 2278 |
const user = userEvent.setup() |
| 2279 |
|
| 2280 |
function User() { |
| 2281 |
const [updateUser] = api.endpoints.updateUser.useMutation() |
| 2282 |
const [successMsg, setSuccessMsg] = useState('') |
| 2283 |
const [errMsg, setErrMsg] = useState('') |
| 2284 |
const [isAborted, setIsAborted] = useState(false) |
| 2285 |
|
| 2286 |
const handleClick = async () => { |
| 2287 |
const res = updateUser({ name: 'Banana' }) |
| 2288 |
|
| 2289 |
// abort the mutation immediately to force an error |
| 2290 |
res.abort() |
| 2291 |
res |
| 2292 |
.unwrap() |
| 2293 |
.then((result) => { |
| 2294 |
setSuccessMsg(`Successfully updated user ${result.name}`) |
| 2295 |
}) |
| 2296 |
.catch((err) => { |
| 2297 |
setErrMsg( |
| 2298 |
`An error has occurred updating user ${res.arg.originalArgs.name}`, |
| 2299 |
) |
| 2300 |
if (err.name === 'AbortError') { |
| 2301 |
setIsAborted(true) |
| 2302 |
} |
| 2303 |
}) |
| 2304 |
} |
| 2305 |
|
| 2306 |
return ( |
| 2307 |
<div> |
| 2308 |
<button onClick={handleClick}>Update User and abort</button> |
| 2309 |
<div>{successMsg}</div> |
| 2310 |
<div>{errMsg}</div> |
| 2311 |
<div>{isAborted ? 'Request was aborted' : ''}</div> |
| 2312 |
</div> |
| 2313 |
) |
| 2314 |
} |
| 2315 |
|
| 2316 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2317 |
expect(screen.queryByText(/An error has occurred/i)).toBeNull() |
| 2318 |
expect(screen.queryByText(/Successfully updated user/i)).toBeNull() |
| 2319 |
expect(screen.queryByText('Request was aborted')).toBeNull() |
| 2320 |
|
| 2321 |
await user.click( |
| 2322 |
screen.getByRole('button', { name: 'Update User and abort' }), |
| 2323 |
) |
| 2324 |
await screen.findByText('An error has occurred updating user Banana') |
| 2325 |
expect(screen.queryByText(/Successfully updated user/i)).toBeNull() |
| 2326 |
screen.getByText('Request was aborted') |
| 2327 |
}) |
| 2328 |
|
| 2329 |
test('useMutation return value contains originalArgs', async () => { |
| 2330 |
const { result } = renderHook( |
| 2331 |
() => api.endpoints.updateUser.useMutation(), |
| 2332 |
{ |
| 2333 |
wrapper: storeRef.wrapper, |
| 2334 |
}, |
| 2335 |
) |
| 2336 |
const arg = { name: 'Foo' } |
| 2337 |
|
| 2338 |
const firstRenderResult = result.current |
| 2339 |
expect(firstRenderResult[1].originalArgs).toBe(undefined) |
| 2340 |
await act(async () => { |
| 2341 |
await firstRenderResult[0](arg) |
| 2342 |
}) |
| 2343 |
const secondRenderResult = result.current |
| 2344 |
expect(firstRenderResult[1].originalArgs).toBe(undefined) |
| 2345 |
expect(secondRenderResult[1].originalArgs).toBe(arg) |
| 2346 |
}) |
| 2347 |
|
| 2348 |
test('`reset` sets state back to original state', async () => { |
| 2349 |
const user = userEvent.setup() |
| 2350 |
|
| 2351 |
function User() { |
| 2352 |
const [updateUser, result] = api.endpoints.updateUser.useMutation() |
| 2353 |
return ( |
| 2354 |
<> |
| 2355 |
<span> |
| 2356 |
{result.isUninitialized |
| 2357 |
? 'isUninitialized' |
| 2358 |
: result.isSuccess |
| 2359 |
? 'isSuccess' |
| 2360 |
: 'other'} |
| 2361 |
</span> |
| 2362 |
<span>{result.originalArgs?.name}</span> |
| 2363 |
<button onClick={() => updateUser({ name: 'Yay' })}>trigger</button> |
| 2364 |
<button onClick={result.reset}>reset</button> |
| 2365 |
</> |
| 2366 |
) |
| 2367 |
} |
| 2368 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2369 |
|
| 2370 |
await screen.findByText(/isUninitialized/i) |
| 2371 |
expect(screen.queryByText('Yay')).toBeNull() |
| 2372 |
expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(0) |
| 2373 |
|
| 2374 |
await user.click(screen.getByRole('button', { name: 'trigger' })) |
| 2375 |
|
| 2376 |
await screen.findByText(/isSuccess/i) |
| 2377 |
expect(screen.queryByText('Yay')).not.toBeNull() |
| 2378 |
expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(1) |
| 2379 |
|
| 2380 |
await user.click(screen.getByRole('button', { name: 'reset' })) |
| 2381 |
|
| 2382 |
await screen.findByText(/isUninitialized/i) |
| 2383 |
expect(screen.queryByText('Yay')).toBeNull() |
| 2384 |
expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(0) |
| 2385 |
}) |
| 2386 |
}) |
| 2387 |
|
| 2388 |
describe('usePrefetch', () => { |
| 2389 |
test('usePrefetch respects force arg', async () => { |
| 2390 |
const user = userEvent.setup() |
| 2391 |
|
| 2392 |
const { usePrefetch } = api |
| 2393 |
const USER_ID = 4 |
| 2394 |
function User() { |
| 2395 |
const { isFetching } = api.endpoints.getUser.useQuery(USER_ID) |
| 2396 |
const prefetchUser = usePrefetch('getUser', { force: true }) |
| 2397 |
|
| 2398 |
return ( |
| 2399 |
<div> |
| 2400 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 2401 |
<button |
| 2402 |
onMouseEnter={() => prefetchUser(USER_ID, { force: true })} |
| 2403 |
data-testid="highPriority" |
| 2404 |
> |
| 2405 |
High priority action intent |
| 2406 |
</button> |
| 2407 |
</div> |
| 2408 |
) |
| 2409 |
} |
| 2410 |
|
| 2411 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2412 |
|
| 2413 |
// Resolve initial query |
| 2414 |
await waitFor(() => |
| 2415 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 2416 |
) |
| 2417 |
|
| 2418 |
await user.hover(screen.getByTestId('highPriority')) |
| 2419 |
|
| 2420 |
expect( |
| 2421 |
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any), |
| 2422 |
).toEqual({ |
| 2423 |
data: { name: 'Timmy' }, |
| 2424 |
endpointName: 'getUser', |
| 2425 |
error: undefined, |
| 2426 |
fulfilledTimeStamp: expect.any(Number), |
| 2427 |
isError: false, |
| 2428 |
isLoading: true, |
| 2429 |
isSuccess: false, |
| 2430 |
isUninitialized: false, |
| 2431 |
originalArgs: USER_ID, |
| 2432 |
requestId: expect.any(String), |
| 2433 |
startedTimeStamp: expect.any(Number), |
| 2434 |
status: QueryStatus.pending, |
| 2435 |
}) |
| 2436 |
|
| 2437 |
await waitFor(() => |
| 2438 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 2439 |
) |
| 2440 |
|
| 2441 |
expect( |
| 2442 |
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any), |
| 2443 |
).toEqual({ |
| 2444 |
data: { name: 'Timmy' }, |
| 2445 |
endpointName: 'getUser', |
| 2446 |
fulfilledTimeStamp: expect.any(Number), |
| 2447 |
isError: false, |
| 2448 |
isLoading: false, |
| 2449 |
isSuccess: true, |
| 2450 |
isUninitialized: false, |
| 2451 |
originalArgs: USER_ID, |
| 2452 |
requestId: expect.any(String), |
| 2453 |
startedTimeStamp: expect.any(Number), |
| 2454 |
status: QueryStatus.fulfilled, |
| 2455 |
}) |
| 2456 |
}) |
| 2457 |
|
| 2458 |
test('usePrefetch does not make an additional request if already in the cache and force=false', async () => { |
| 2459 |
const user = userEvent.setup() |
| 2460 |
|
| 2461 |
const { usePrefetch } = api |
| 2462 |
const USER_ID = 2 |
| 2463 |
|
| 2464 |
function User() { |
| 2465 |
// Load the initial query |
| 2466 |
const { isFetching } = api.endpoints.getUser.useQuery(USER_ID) |
| 2467 |
const prefetchUser = usePrefetch('getUser', { force: false }) |
| 2468 |
|
| 2469 |
return ( |
| 2470 |
<div> |
| 2471 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 2472 |
<button |
| 2473 |
onMouseEnter={() => prefetchUser(USER_ID)} |
| 2474 |
data-testid="lowPriority" |
| 2475 |
> |
| 2476 |
Low priority user action intent |
| 2477 |
</button> |
| 2478 |
</div> |
| 2479 |
) |
| 2480 |
} |
| 2481 |
|
| 2482 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2483 |
|
| 2484 |
// Let the initial query resolve |
| 2485 |
await waitFor(() => |
| 2486 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 2487 |
) |
| 2488 |
// Try to prefetch what we just loaded |
| 2489 |
await user.hover(screen.getByTestId('lowPriority')) |
| 2490 |
|
| 2491 |
expect( |
| 2492 |
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any), |
| 2493 |
).toEqual({ |
| 2494 |
data: { name: 'Timmy' }, |
| 2495 |
endpointName: 'getUser', |
| 2496 |
fulfilledTimeStamp: expect.any(Number), |
| 2497 |
isError: false, |
| 2498 |
isLoading: false, |
| 2499 |
isSuccess: true, |
| 2500 |
isUninitialized: false, |
| 2501 |
originalArgs: USER_ID, |
| 2502 |
requestId: expect.any(String), |
| 2503 |
startedTimeStamp: expect.any(Number), |
| 2504 |
status: QueryStatus.fulfilled, |
| 2505 |
}) |
| 2506 |
|
| 2507 |
await waitMs() |
| 2508 |
|
| 2509 |
expect( |
| 2510 |
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any), |
| 2511 |
).toEqual({ |
| 2512 |
data: { name: 'Timmy' }, |
| 2513 |
endpointName: 'getUser', |
| 2514 |
fulfilledTimeStamp: expect.any(Number), |
| 2515 |
isError: false, |
| 2516 |
isLoading: false, |
| 2517 |
isSuccess: true, |
| 2518 |
isUninitialized: false, |
| 2519 |
originalArgs: USER_ID, |
| 2520 |
requestId: expect.any(String), |
| 2521 |
startedTimeStamp: expect.any(Number), |
| 2522 |
status: QueryStatus.fulfilled, |
| 2523 |
}) |
| 2524 |
}) |
| 2525 |
|
| 2526 |
test('usePrefetch respects ifOlderThan when it evaluates to true', async () => { |
| 2527 |
const user = userEvent.setup() |
| 2528 |
|
| 2529 |
const { usePrefetch } = api |
| 2530 |
const USER_ID = 47 |
| 2531 |
|
| 2532 |
function User() { |
| 2533 |
// Load the initial query |
| 2534 |
const { isFetching } = api.endpoints.getUser.useQuery(USER_ID) |
| 2535 |
const prefetchUser = usePrefetch('getUser', { ifOlderThan: 0.2 }) |
| 2536 |
|
| 2537 |
return ( |
| 2538 |
<div> |
| 2539 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 2540 |
<button |
| 2541 |
onMouseEnter={() => prefetchUser(USER_ID)} |
| 2542 |
data-testid="lowPriority" |
| 2543 |
> |
| 2544 |
Low priority user action intent |
| 2545 |
</button> |
| 2546 |
</div> |
| 2547 |
) |
| 2548 |
} |
| 2549 |
|
| 2550 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2551 |
|
| 2552 |
await waitFor(() => |
| 2553 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 2554 |
) |
| 2555 |
|
| 2556 |
// Wait 400ms, making it respect ifOlderThan |
| 2557 |
await waitMs(400) |
| 2558 |
|
| 2559 |
// This should run the query being that we're past the threshold |
| 2560 |
await user.hover(screen.getByTestId('lowPriority')) |
| 2561 |
|
| 2562 |
expect( |
| 2563 |
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any), |
| 2564 |
).toEqual({ |
| 2565 |
data: { name: 'Timmy' }, |
| 2566 |
endpointName: 'getUser', |
| 2567 |
fulfilledTimeStamp: expect.any(Number), |
| 2568 |
isError: false, |
| 2569 |
isLoading: true, |
| 2570 |
isSuccess: false, |
| 2571 |
isUninitialized: false, |
| 2572 |
originalArgs: USER_ID, |
| 2573 |
requestId: expect.any(String), |
| 2574 |
startedTimeStamp: expect.any(Number), |
| 2575 |
status: QueryStatus.pending, |
| 2576 |
}) |
| 2577 |
|
| 2578 |
await waitFor(() => |
| 2579 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 2580 |
) |
| 2581 |
|
| 2582 |
expect( |
| 2583 |
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any), |
| 2584 |
).toEqual({ |
| 2585 |
data: { name: 'Timmy' }, |
| 2586 |
endpointName: 'getUser', |
| 2587 |
fulfilledTimeStamp: expect.any(Number), |
| 2588 |
isError: false, |
| 2589 |
isLoading: false, |
| 2590 |
isSuccess: true, |
| 2591 |
isUninitialized: false, |
| 2592 |
originalArgs: USER_ID, |
| 2593 |
requestId: expect.any(String), |
| 2594 |
startedTimeStamp: expect.any(Number), |
| 2595 |
status: QueryStatus.fulfilled, |
| 2596 |
}) |
| 2597 |
}) |
| 2598 |
|
| 2599 |
test('usePrefetch returns the last success result when ifOlderThan evalutes to false', async () => { |
| 2600 |
const user = userEvent.setup() |
| 2601 |
|
| 2602 |
const { usePrefetch } = api |
| 2603 |
const USER_ID = 2 |
| 2604 |
|
| 2605 |
function User() { |
| 2606 |
// Load the initial query |
| 2607 |
const { isFetching } = api.endpoints.getUser.useQuery(USER_ID) |
| 2608 |
const prefetchUser = usePrefetch('getUser', { ifOlderThan: 10 }) |
| 2609 |
|
| 2610 |
return ( |
| 2611 |
<div> |
| 2612 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 2613 |
<button |
| 2614 |
onMouseEnter={() => prefetchUser(USER_ID)} |
| 2615 |
data-testid="lowPriority" |
| 2616 |
> |
| 2617 |
Low priority user action intent |
| 2618 |
</button> |
| 2619 |
</div> |
| 2620 |
) |
| 2621 |
} |
| 2622 |
|
| 2623 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2624 |
|
| 2625 |
await waitFor(() => |
| 2626 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 2627 |
) |
| 2628 |
await waitMs() |
| 2629 |
|
| 2630 |
// Get a snapshot of the last result |
| 2631 |
const latestQueryData = api.endpoints.getUser.select(USER_ID)( |
| 2632 |
storeRef.store.getState() as any, |
| 2633 |
) |
| 2634 |
|
| 2635 |
await user.hover(screen.getByTestId('lowPriority')) |
| 2636 |
|
| 2637 |
// Serve up the result from the cache being that the condition wasn't met |
| 2638 |
expect( |
| 2639 |
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any), |
| 2640 |
).toEqual(latestQueryData) |
| 2641 |
}) |
| 2642 |
|
| 2643 |
test('usePrefetch executes a query even if conditions fail when the cache is empty', async () => { |
| 2644 |
const user = userEvent.setup() |
| 2645 |
|
| 2646 |
const { usePrefetch } = api |
| 2647 |
const USER_ID = 2 |
| 2648 |
|
| 2649 |
function User() { |
| 2650 |
const prefetchUser = usePrefetch('getUser', { ifOlderThan: 10 }) |
| 2651 |
|
| 2652 |
return ( |
| 2653 |
<div> |
| 2654 |
<button |
| 2655 |
onMouseEnter={() => prefetchUser(USER_ID)} |
| 2656 |
data-testid="lowPriority" |
| 2657 |
> |
| 2658 |
Low priority user action intent |
| 2659 |
</button> |
| 2660 |
</div> |
| 2661 |
) |
| 2662 |
} |
| 2663 |
|
| 2664 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2665 |
|
| 2666 |
await user.hover(screen.getByTestId('lowPriority')) |
| 2667 |
|
| 2668 |
expect( |
| 2669 |
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState()), |
| 2670 |
).toEqual({ |
| 2671 |
endpointName: 'getUser', |
| 2672 |
isError: false, |
| 2673 |
isLoading: true, |
| 2674 |
isSuccess: false, |
| 2675 |
isUninitialized: false, |
| 2676 |
originalArgs: USER_ID, |
| 2677 |
requestId: expect.any(String), |
| 2678 |
startedTimeStamp: expect.any(Number), |
| 2679 |
status: 'pending', |
| 2680 |
}) |
| 2681 |
}) |
| 2682 |
}) |
| 2683 |
|
| 2684 |
describe('useQuery and useMutation invalidation behavior', () => { |
| 2685 |
const api = createApi({ |
| 2686 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }), |
| 2687 |
tagTypes: ['User'], |
| 2688 |
endpoints: (build) => ({ |
| 2689 |
checkSession: build.query<any, void>({ |
| 2690 |
query: () => '/me', |
| 2691 |
providesTags: ['User'], |
| 2692 |
}), |
| 2693 |
login: build.mutation<any, any>({ |
| 2694 |
query: () => ({ url: '/login', method: 'POST' }), |
| 2695 |
invalidatesTags: ['User'], |
| 2696 |
}), |
| 2697 |
}), |
| 2698 |
}) |
| 2699 |
|
| 2700 |
const storeRef = setupApiStore(api, { ...actionsReducer }) |
| 2701 |
test('initially failed useQueries that provide an tag will refetch after a mutation invalidates it', async () => { |
| 2702 |
const checkSessionData = { name: 'matt' } |
| 2703 |
server.use( |
| 2704 |
http.get( |
| 2705 |
'https://example.com/me', |
| 2706 |
() => { |
| 2707 |
return HttpResponse.json(null, { status: 500 }) |
| 2708 |
}, |
| 2709 |
{ once: true }, |
| 2710 |
), |
| 2711 |
http.get('https://example.com/me', () => { |
| 2712 |
return HttpResponse.json(checkSessionData) |
| 2713 |
}), |
| 2714 |
http.post('https://example.com/login', () => { |
| 2715 |
return HttpResponse.json(null, { status: 200 }) |
| 2716 |
}), |
| 2717 |
) |
| 2718 |
let data, isLoading, isError |
| 2719 |
function User() { |
| 2720 |
;({ data, isError, isLoading } = api.endpoints.checkSession.useQuery()) |
| 2721 |
const [login, { isLoading: loginLoading }] = |
| 2722 |
api.endpoints.login.useMutation() |
| 2723 |
|
| 2724 |
return ( |
| 2725 |
<div> |
| 2726 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 2727 |
<div data-testid="isError">{String(isError)}</div> |
| 2728 |
<div data-testid="user">{JSON.stringify(data)}</div> |
| 2729 |
<div data-testid="loginLoading">{String(loginLoading)}</div> |
| 2730 |
<button onClick={() => login(null)}>Login</button> |
| 2731 |
</div> |
| 2732 |
) |
| 2733 |
} |
| 2734 |
|
| 2735 |
render(<User />, { wrapper: storeRef.wrapper }) |
| 2736 |
await waitFor(() => |
| 2737 |
expect(screen.getByTestId('isLoading').textContent).toBe('true'), |
| 2738 |
) |
| 2739 |
await waitFor(() => |
| 2740 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 2741 |
) |
| 2742 |
await waitFor(() => |
| 2743 |
expect(screen.getByTestId('isError').textContent).toBe('true'), |
| 2744 |
) |
| 2745 |
await waitFor(() => |
| 2746 |
expect(screen.getByTestId('user').textContent).toBe(''), |
| 2747 |
) |
| 2748 |
|
| 2749 |
fireEvent.click(screen.getByRole('button', { name: /Login/i })) |
| 2750 |
|
| 2751 |
await waitFor(() => |
| 2752 |
expect(screen.getByTestId('loginLoading').textContent).toBe('true'), |
| 2753 |
) |
| 2754 |
await waitFor(() => |
| 2755 |
expect(screen.getByTestId('loginLoading').textContent).toBe('false'), |
| 2756 |
) |
| 2757 |
// login mutation will cause the original errored out query to refire, clearing the error and setting the user |
| 2758 |
await waitFor(() => |
| 2759 |
expect(screen.getByTestId('isError').textContent).toBe('false'), |
| 2760 |
) |
| 2761 |
await waitFor(() => |
| 2762 |
expect(screen.getByTestId('user').textContent).toBe( |
| 2763 |
JSON.stringify(checkSessionData), |
| 2764 |
), |
| 2765 |
) |
| 2766 |
|
| 2767 |
const { checkSession, login } = api.endpoints |
| 2768 |
expect(storeRef.store.getState().actions).toMatchSequence( |
| 2769 |
api.internalActions.middlewareRegistered.match, |
| 2770 |
checkSession.matchPending, |
| 2771 |
checkSession.matchRejected, |
| 2772 |
login.matchPending, |
| 2773 |
login.matchFulfilled, |
| 2774 |
checkSession.matchPending, |
| 2775 |
checkSession.matchFulfilled, |
| 2776 |
) |
| 2777 |
}) |
| 2778 |
}) |
| 2779 |
}) |
| 2780 |
|
| 2781 |
describe('hooks with createApi defaults set', () => { |
| 2782 |
const defaultApi = createApi({ |
| 2783 |
baseQuery: async (arg: any) => { |
| 2784 |
await waitMs() |
| 2785 |
if ('amount' in arg?.body) { |
| 2786 |
amount += 1 |
| 2787 |
} |
| 2788 |
return { |
| 2789 |
data: arg?.body |
| 2790 |
? { ...arg.body, ...(amount ? { amount } : {}) } |
| 2791 |
: undefined, |
| 2792 |
} |
| 2793 |
}, |
| 2794 |
endpoints: (build) => ({ |
| 2795 |
getIncrementedAmount: build.query<any, void>({ |
| 2796 |
query: () => ({ |
| 2797 |
url: '', |
| 2798 |
body: { |
| 2799 |
amount, |
| 2800 |
}, |
| 2801 |
}), |
| 2802 |
}), |
| 2803 |
}), |
| 2804 |
refetchOnMountOrArgChange: true, |
| 2805 |
}) |
| 2806 |
|
| 2807 |
const storeRef = setupApiStore(defaultApi) |
| 2808 |
test('useQuery hook respects refetchOnMountOrArgChange: true when set in createApi options', async () => { |
| 2809 |
let data, isLoading, isFetching |
| 2810 |
|
| 2811 |
function User() { |
| 2812 |
;({ data, isLoading } = |
| 2813 |
defaultApi.endpoints.getIncrementedAmount.useQuery()) |
| 2814 |
return ( |
| 2815 |
<div> |
| 2816 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 2817 |
<div data-testid="amount">{String(data?.amount)}</div> |
| 2818 |
</div> |
| 2819 |
) |
| 2820 |
} |
| 2821 |
|
| 2822 |
const { unmount } = render(<User />, { wrapper: storeRef.wrapper }) |
| 2823 |
|
| 2824 |
await waitFor(() => |
| 2825 |
expect(screen.getByTestId('isLoading').textContent).toBe('true'), |
| 2826 |
) |
| 2827 |
await waitFor(() => |
| 2828 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 2829 |
) |
| 2830 |
|
| 2831 |
await waitFor(() => |
| 2832 |
expect(screen.getByTestId('amount').textContent).toBe('1'), |
| 2833 |
) |
| 2834 |
|
| 2835 |
unmount() |
| 2836 |
|
| 2837 |
function OtherUser() { |
| 2838 |
;({ data, isFetching } = |
| 2839 |
defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, { |
| 2840 |
refetchOnMountOrArgChange: true, |
| 2841 |
})) |
| 2842 |
return ( |
| 2843 |
<div> |
| 2844 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 2845 |
<div data-testid="amount">{String(data?.amount)}</div> |
| 2846 |
</div> |
| 2847 |
) |
| 2848 |
} |
| 2849 |
|
| 2850 |
render(<OtherUser />, { wrapper: storeRef.wrapper }) |
| 2851 |
// Let's make sure we actually fetch, and we increment |
| 2852 |
await waitFor(() => |
| 2853 |
expect(screen.getByTestId('isFetching').textContent).toBe('true'), |
| 2854 |
) |
| 2855 |
await waitFor(() => |
| 2856 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 2857 |
) |
| 2858 |
|
| 2859 |
await waitFor(() => |
| 2860 |
expect(screen.getByTestId('amount').textContent).toBe('2'), |
| 2861 |
) |
| 2862 |
}) |
| 2863 |
|
| 2864 |
test('useQuery hook overrides default refetchOnMountOrArgChange: false that was set by createApi', async () => { |
| 2865 |
let data, isLoading, isFetching |
| 2866 |
|
| 2867 |
function User() { |
| 2868 |
;({ data, isLoading } = |
| 2869 |
defaultApi.endpoints.getIncrementedAmount.useQuery()) |
| 2870 |
return ( |
| 2871 |
<div> |
| 2872 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 2873 |
<div data-testid="amount">{String(data?.amount)}</div> |
| 2874 |
</div> |
| 2875 |
) |
| 2876 |
} |
| 2877 |
|
| 2878 |
let { unmount } = render(<User />, { wrapper: storeRef.wrapper }) |
| 2879 |
|
| 2880 |
await waitFor(() => |
| 2881 |
expect(screen.getByTestId('isLoading').textContent).toBe('true'), |
| 2882 |
) |
| 2883 |
await waitFor(() => |
| 2884 |
expect(screen.getByTestId('isLoading').textContent).toBe('false'), |
| 2885 |
) |
| 2886 |
|
| 2887 |
await waitFor(() => |
| 2888 |
expect(screen.getByTestId('amount').textContent).toBe('1'), |
| 2889 |
) |
| 2890 |
|
| 2891 |
unmount() |
| 2892 |
|
| 2893 |
function OtherUser() { |
| 2894 |
;({ data, isFetching } = |
| 2895 |
defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, { |
| 2896 |
refetchOnMountOrArgChange: false, |
| 2897 |
})) |
| 2898 |
return ( |
| 2899 |
<div> |
| 2900 |
<div data-testid="isFetching">{String(isFetching)}</div> |
| 2901 |
<div data-testid="amount">{String(data?.amount)}</div> |
| 2902 |
</div> |
| 2903 |
) |
| 2904 |
} |
| 2905 |
|
| 2906 |
render(<OtherUser />, { wrapper: storeRef.wrapper }) |
| 2907 |
|
| 2908 |
await waitFor(() => |
| 2909 |
expect(screen.getByTestId('isFetching').textContent).toBe('false'), |
| 2910 |
) |
| 2911 |
await waitFor(() => |
| 2912 |
expect(screen.getByTestId('amount').textContent).toBe('1'), |
| 2913 |
) |
| 2914 |
}) |
| 2915 |
|
| 2916 |
describe('selectFromResult (query) behaviors', () => { |
| 2917 |
let startingId = 3 |
| 2918 |
const initialPosts = [ |
| 2919 |
{ id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() }, |
| 2920 |
{ |
| 2921 |
id: 2, |
| 2922 |
name: 'A post about rtk-query', |
| 2923 |
fetched_at: new Date().toUTCString(), |
| 2924 |
}, |
| 2925 |
] |
| 2926 |
let posts = [] as typeof initialPosts |
| 2927 |
|
| 2928 |
beforeEach(() => { |
| 2929 |
startingId = 3 |
| 2930 |
posts = [...initialPosts] |
| 2931 |
|
| 2932 |
const handlers = [ |
| 2933 |
http.get('https://example.com/posts', () => { |
| 2934 |
return HttpResponse.json(posts) |
| 2935 |
}), |
| 2936 |
http.put<{ id: string }, Partial<Post>>( |
| 2937 |
'https://example.com/post/:id', |
| 2938 |
async ({ request, params }) => { |
| 2939 |
const body = await request.json() |
| 2940 |
const id = Number(params.id) |
| 2941 |
const idx = posts.findIndex((post) => post.id === id) |
| 2942 |
|
| 2943 |
const newPosts = posts.map((post, index) => |
| 2944 |
index !== idx |
| 2945 |
? post |
| 2946 |
: { |
| 2947 |
...body, |
| 2948 |
id, |
| 2949 |
name: body?.name || post.name, |
| 2950 |
fetched_at: new Date().toUTCString(), |
| 2951 |
}, |
| 2952 |
) |
| 2953 |
posts = [...newPosts] |
| 2954 |
|
| 2955 |
return HttpResponse.json(posts) |
| 2956 |
}, |
| 2957 |
), |
| 2958 |
http.post<any, Omit<Post, 'id'>>( |
| 2959 |
'https://example.com/post', |
| 2960 |
async ({ request }) => { |
| 2961 |
const body = await request.json() |
| 2962 |
const post = body |
| 2963 |
startingId += 1 |
| 2964 |
posts.concat({ |
| 2965 |
...post, |
| 2966 |
fetched_at: new Date().toISOString(), |
| 2967 |
id: startingId, |
| 2968 |
}) |
| 2969 |
return HttpResponse.json(posts) |
| 2970 |
}, |
| 2971 |
), |
| 2972 |
] |
| 2973 |
|
| 2974 |
server.use(...handlers) |
| 2975 |
}) |
| 2976 |
|
| 2977 |
interface Post { |
| 2978 |
id: number |
| 2979 |
name: string |
| 2980 |
fetched_at: string |
| 2981 |
} |
| 2982 |
|
| 2983 |
type PostsResponse = Post[] |
| 2984 |
|
| 2985 |
const api = createApi({ |
| 2986 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }), |
| 2987 |
tagTypes: ['Posts'], |
| 2988 |
endpoints: (build) => ({ |
| 2989 |
getPosts: build.query<PostsResponse, void>({ |
| 2990 |
query: () => ({ url: 'posts' }), |
| 2991 |
providesTags: (result) => |
| 2992 |
result ? result.map(({ id }) => ({ type: 'Posts', id })) : [], |
| 2993 |
}), |
| 2994 |
updatePost: build.mutation<Post, Partial<Post>>({ |
| 2995 |
query: ({ id, ...body }) => ({ |
| 2996 |
url: `post/${id}`, |
| 2997 |
method: 'PUT', |
| 2998 |
body, |
| 2999 |
}), |
| 3000 |
invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }], |
| 3001 |
}), |
| 3002 |
addPost: build.mutation<Post, Partial<Post>>({ |
| 3003 |
query: (body) => ({ |
| 3004 |
url: `post`, |
| 3005 |
method: 'POST', |
| 3006 |
body, |
| 3007 |
}), |
| 3008 |
invalidatesTags: ['Posts'], |
| 3009 |
}), |
| 3010 |
}), |
| 3011 |
}) |
| 3012 |
|
| 3013 |
const counterSlice = createSlice({ |
| 3014 |
name: 'counter', |
| 3015 |
initialState: { count: 0 }, |
| 3016 |
reducers: { |
| 3017 |
increment(state) { |
| 3018 |
state.count++ |
| 3019 |
}, |
| 3020 |
}, |
| 3021 |
}) |
| 3022 |
|
| 3023 |
const storeRef = setupApiStore(api, { |
| 3024 |
counter: counterSlice.reducer, |
| 3025 |
}) |
| 3026 |
|
| 3027 |
test('useQueryState serves a deeply memoized value and does not rerender unnecessarily', async () => { |
| 3028 |
function Posts() { |
| 3029 |
const { data: posts } = api.endpoints.getPosts.useQuery() |
| 3030 |
const [addPost] = api.endpoints.addPost.useMutation() |
| 3031 |
return ( |
| 3032 |
<div> |
| 3033 |
<button |
| 3034 |
data-testid="addPost" |
| 3035 |
onClick={() => addPost({ name: `some text ${posts?.length}` })} |
| 3036 |
> |
| 3037 |
Add random post |
| 3038 |
</button> |
| 3039 |
</div> |
| 3040 |
) |
| 3041 |
} |
| 3042 |
|
| 3043 |
function SelectedPost() { |
| 3044 |
const { post } = api.endpoints.getPosts.useQueryState(undefined, { |
| 3045 |
selectFromResult: ({ data }) => ({ |
| 3046 |
post: data?.find((post) => post.id === 1), |
| 3047 |
}), |
| 3048 |
}) |
| 3049 |
getRenderCount = useRenderCounter() |
| 3050 |
|
| 3051 |
/** |
| 3052 |
* Notes on the renderCount behavior |
| 3053 |
* |
| 3054 |
* We initialize at 0, and the first render will bump that 1 while post is `undefined`. |
| 3055 |
* Once the request resolves, it will be at 2. What we're looking for is to make sure that |
| 3056 |
* any requests that don't directly change the value of the selected item will have no impact |
| 3057 |
* on rendering. |
| 3058 |
*/ |
| 3059 |
|
| 3060 |
return <div /> |
| 3061 |
} |
| 3062 |
|
| 3063 |
render( |
| 3064 |
<div> |
| 3065 |
<Posts /> |
| 3066 |
<SelectedPost /> |
| 3067 |
</div>, |
| 3068 |
{ wrapper: storeRef.wrapper }, |
| 3069 |
) |
| 3070 |
|
| 3071 |
expect(getRenderCount()).toBe(1) |
| 3072 |
|
| 3073 |
const addBtn = screen.getByTestId('addPost') |
| 3074 |
|
| 3075 |
await waitFor(() => expect(getRenderCount()).toBe(2)) |
| 3076 |
|
| 3077 |
fireEvent.click(addBtn) |
| 3078 |
await waitFor(() => expect(getRenderCount()).toBe(2)) |
| 3079 |
// We fire off a few requests that would typically cause a rerender as JSON.parse() on a request would always be a new object. |
| 3080 |
fireEvent.click(addBtn) |
| 3081 |
fireEvent.click(addBtn) |
| 3082 |
await waitFor(() => expect(getRenderCount()).toBe(2)) |
| 3083 |
// Being that it didn't rerender, we can be assured that the behavior is correct |
| 3084 |
}) |
| 3085 |
|
| 3086 |
/** |
| 3087 |
* This test shows that even though a user can select a specific post, the fetching/loading flags |
| 3088 |
* will still cause rerenders for the query. This should show that if you're using selectFromResult, |
| 3089 |
* the 'performance' value comes with selecting _only_ the data. |
| 3090 |
*/ |
| 3091 |
test('useQuery with selectFromResult with all flags destructured rerenders like the default useQuery behavior', async () => { |
| 3092 |
function Posts() { |
| 3093 |
const { data: posts } = api.endpoints.getPosts.useQuery() |
| 3094 |
const [addPost] = api.endpoints.addPost.useMutation() |
| 3095 |
getRenderCount = useRenderCounter() |
| 3096 |
return ( |
| 3097 |
<div> |
| 3098 |
<button |
| 3099 |
data-testid="addPost" |
| 3100 |
onClick={() => |
| 3101 |
addPost({ |
| 3102 |
name: `some text ${posts?.length}`, |
| 3103 |
fetched_at: new Date().toISOString(), |
| 3104 |
}) |
| 3105 |
} |
| 3106 |
> |
| 3107 |
Add random post |
| 3108 |
</button> |
| 3109 |
</div> |
| 3110 |
) |
| 3111 |
} |
| 3112 |
|
| 3113 |
function SelectedPost() { |
| 3114 |
getRenderCount = useRenderCounter() |
| 3115 |
|
| 3116 |
const { post } = api.endpoints.getPosts.useQuery(undefined, { |
| 3117 |
selectFromResult: ({ |
| 3118 |
data, |
| 3119 |
isUninitialized, |
| 3120 |
isLoading, |
| 3121 |
isFetching, |
| 3122 |
isSuccess, |
| 3123 |
isError, |
| 3124 |
}) => ({ |
| 3125 |
post: data?.find((post) => post.id === 1), |
| 3126 |
isUninitialized, |
| 3127 |
isLoading, |
| 3128 |
isFetching, |
| 3129 |
isSuccess, |
| 3130 |
isError, |
| 3131 |
}), |
| 3132 |
}) |
| 3133 |
|
| 3134 |
return <div /> |
| 3135 |
} |
| 3136 |
|
| 3137 |
render( |
| 3138 |
<div> |
| 3139 |
<Posts /> |
| 3140 |
<SelectedPost /> |
| 3141 |
</div>, |
| 3142 |
{ wrapper: storeRef.wrapper }, |
| 3143 |
) |
| 3144 |
expect(getRenderCount()).toBe(2) |
| 3145 |
|
| 3146 |
const addBtn = screen.getByTestId('addPost') |
| 3147 |
|
| 3148 |
await waitFor(() => expect(getRenderCount()).toBe(3)) |
| 3149 |
|
| 3150 |
fireEvent.click(addBtn) |
| 3151 |
await waitFor(() => expect(getRenderCount()).toBe(5)) |
| 3152 |
fireEvent.click(addBtn) |
| 3153 |
fireEvent.click(addBtn) |
| 3154 |
await waitFor(() => expect(getRenderCount()).toBe(7)) |
| 3155 |
}) |
| 3156 |
|
| 3157 |
test('useQuery with selectFromResult option serves a deeply memoized value and does not rerender unnecessarily', async () => { |
| 3158 |
function Posts() { |
| 3159 |
const { data: posts } = api.endpoints.getPosts.useQuery() |
| 3160 |
const [addPost] = api.endpoints.addPost.useMutation() |
| 3161 |
return ( |
| 3162 |
<div> |
| 3163 |
<button |
| 3164 |
data-testid="addPost" |
| 3165 |
onClick={() => |
| 3166 |
addPost({ |
| 3167 |
name: `some text ${posts?.length}`, |
| 3168 |
fetched_at: new Date().toISOString(), |
| 3169 |
}) |
| 3170 |
} |
| 3171 |
> |
| 3172 |
Add random post |
| 3173 |
</button> |
| 3174 |
</div> |
| 3175 |
) |
| 3176 |
} |
| 3177 |
|
| 3178 |
function SelectedPost() { |
| 3179 |
getRenderCount = useRenderCounter() |
| 3180 |
const { post } = api.endpoints.getPosts.useQuery(undefined, { |
| 3181 |
selectFromResult: ({ data }) => ({ |
| 3182 |
post: data?.find((post) => post.id === 1), |
| 3183 |
}), |
| 3184 |
}) |
| 3185 |
|
| 3186 |
return <div /> |
| 3187 |
} |
| 3188 |
|
| 3189 |
render( |
| 3190 |
<div> |
| 3191 |
<Posts /> |
| 3192 |
<SelectedPost /> |
| 3193 |
</div>, |
| 3194 |
{ wrapper: storeRef.wrapper }, |
| 3195 |
) |
| 3196 |
expect(getRenderCount()).toBe(1) |
| 3197 |
|
| 3198 |
const addBtn = screen.getByTestId('addPost') |
| 3199 |
|
| 3200 |
await waitFor(() => expect(getRenderCount()).toBe(2)) |
| 3201 |
|
| 3202 |
fireEvent.click(addBtn) |
| 3203 |
await waitFor(() => expect(getRenderCount()).toBe(2)) |
| 3204 |
fireEvent.click(addBtn) |
| 3205 |
fireEvent.click(addBtn) |
| 3206 |
await waitFor(() => expect(getRenderCount()).toBe(2)) |
| 3207 |
}) |
| 3208 |
|
| 3209 |
test('useQuery with selectFromResult option serves a deeply memoized value, then ONLY updates when the underlying data changes', async () => { |
| 3210 |
let expectablePost: Post | undefined |
| 3211 |
function Posts() { |
| 3212 |
const { data: posts } = api.endpoints.getPosts.useQuery() |
| 3213 |
const [addPost] = api.endpoints.addPost.useMutation() |
| 3214 |
const [updatePost] = api.endpoints.updatePost.useMutation() |
| 3215 |
|
| 3216 |
return ( |
| 3217 |
<div> |
| 3218 |
<button |
| 3219 |
data-testid="addPost" |
| 3220 |
onClick={() => |
| 3221 |
addPost({ |
| 3222 |
name: `some text ${posts?.length}`, |
| 3223 |
fetched_at: new Date().toISOString(), |
| 3224 |
}) |
| 3225 |
} |
| 3226 |
> |
| 3227 |
Add random post |
| 3228 |
</button> |
| 3229 |
<button |
| 3230 |
data-testid="updatePost" |
| 3231 |
onClick={() => updatePost({ id: 1, name: 'supercoooll!' })} |
| 3232 |
> |
| 3233 |
Update post |
| 3234 |
</button> |
| 3235 |
</div> |
| 3236 |
) |
| 3237 |
} |
| 3238 |
|
| 3239 |
function SelectedPost() { |
| 3240 |
const { post } = api.endpoints.getPosts.useQuery(undefined, { |
| 3241 |
selectFromResult: ({ data }) => ({ |
| 3242 |
post: data?.find((post) => post.id === 1), |
| 3243 |
}), |
| 3244 |
}) |
| 3245 |
getRenderCount = useRenderCounter() |
| 3246 |
|
| 3247 |
useEffect(() => { |
| 3248 |
expectablePost = post |
| 3249 |
}, [post]) |
| 3250 |
|
| 3251 |
return ( |
| 3252 |
<div> |
| 3253 |
<div data-testid="postName">{post?.name}</div> |
| 3254 |
</div> |
| 3255 |
) |
| 3256 |
} |
| 3257 |
|
| 3258 |
render( |
| 3259 |
<div> |
| 3260 |
<Posts /> |
| 3261 |
<SelectedPost /> |
| 3262 |
</div>, |
| 3263 |
{ wrapper: storeRef.wrapper }, |
| 3264 |
) |
| 3265 |
expect(getRenderCount()).toBe(1) |
| 3266 |
|
| 3267 |
const addBtn = screen.getByTestId('addPost') |
| 3268 |
const updateBtn = screen.getByTestId('updatePost') |
| 3269 |
|
| 3270 |
fireEvent.click(addBtn) |
| 3271 |
await waitFor(() => expect(getRenderCount()).toBe(2)) |
| 3272 |
fireEvent.click(addBtn) |
| 3273 |
fireEvent.click(addBtn) |
| 3274 |
await waitFor(() => expect(getRenderCount()).toBe(2)) |
| 3275 |
|
| 3276 |
fireEvent.click(updateBtn) |
| 3277 |
await waitFor(() => expect(getRenderCount()).toBe(3)) |
| 3278 |
expect(expectablePost?.name).toBe('supercoooll!') |
| 3279 |
|
| 3280 |
fireEvent.click(addBtn) |
| 3281 |
await waitFor(() => expect(getRenderCount()).toBe(3)) |
| 3282 |
}) |
| 3283 |
|
| 3284 |
test('useQuery with selectFromResult option does not update when unrelated data in the store changes', async () => { |
| 3285 |
function Posts() { |
| 3286 |
const { posts } = api.endpoints.getPosts.useQuery(undefined, { |
| 3287 |
selectFromResult: ({ data }) => ({ |
| 3288 |
// Intentionally use an unstable reference to force a rerender |
| 3289 |
posts: data?.filter((post) => post.name.includes('post')), |
| 3290 |
}), |
| 3291 |
}) |
| 3292 |
|
| 3293 |
getRenderCount = useRenderCounter() |
| 3294 |
|
| 3295 |
return ( |
| 3296 |
<div> |
| 3297 |
{posts?.map((post) => <div key={post.id}>{post.name}</div>)} |
| 3298 |
</div> |
| 3299 |
) |
| 3300 |
} |
| 3301 |
|
| 3302 |
function CounterButton() { |
| 3303 |
return ( |
| 3304 |
<div |
| 3305 |
data-testid="incrementButton" |
| 3306 |
onClick={() => |
| 3307 |
storeRef.store.dispatch(counterSlice.actions.increment()) |
| 3308 |
} |
| 3309 |
> |
| 3310 |
Increment Count |
| 3311 |
</div> |
| 3312 |
) |
| 3313 |
} |
| 3314 |
|
| 3315 |
render( |
| 3316 |
<div> |
| 3317 |
<Posts /> |
| 3318 |
<CounterButton /> |
| 3319 |
</div>, |
| 3320 |
{ wrapper: storeRef.wrapper }, |
| 3321 |
) |
| 3322 |
|
| 3323 |
await waitFor(() => expect(getRenderCount()).toBe(2)) |
| 3324 |
|
| 3325 |
const incrementBtn = screen.getByTestId('incrementButton') |
| 3326 |
fireEvent.click(incrementBtn) |
| 3327 |
expect(getRenderCount()).toBe(2) |
| 3328 |
}) |
| 3329 |
|
| 3330 |
test('useQuery with selectFromResult option has a type error if the result is not an object', async () => { |
| 3331 |
function SelectedPost() { |
| 3332 |
const res2 = api.endpoints.getPosts.useQuery(undefined, { |
| 3333 |
// selectFromResult must always return an object |
| 3334 |
selectFromResult: ({ data }) => ({ size: data?.length ?? 0 }), |
| 3335 |
}) |
| 3336 |
|
| 3337 |
return ( |
| 3338 |
<div> |
| 3339 |
<div data-testid="size2">{res2.size}</div> |
| 3340 |
</div> |
| 3341 |
) |
| 3342 |
} |
| 3343 |
|
| 3344 |
render( |
| 3345 |
<div> |
| 3346 |
<SelectedPost /> |
| 3347 |
</div>, |
| 3348 |
{ wrapper: storeRef.wrapper }, |
| 3349 |
) |
| 3350 |
|
| 3351 |
expect(screen.getByTestId('size2').textContent).toBe('0') |
| 3352 |
}) |
| 3353 |
}) |
| 3354 |
|
| 3355 |
describe('selectFromResult (mutation) behavior', () => { |
| 3356 |
const api = createApi({ |
| 3357 |
baseQuery: async (arg: any) => { |
| 3358 |
await waitMs() |
| 3359 |
if ('amount' in arg?.body) { |
| 3360 |
amount += 1 |
| 3361 |
} |
| 3362 |
return { |
| 3363 |
data: arg?.body |
| 3364 |
? { ...arg.body, ...(amount ? { amount } : {}) } |
| 3365 |
: undefined, |
| 3366 |
} |
| 3367 |
}, |
| 3368 |
endpoints: (build) => ({ |
| 3369 |
increment: build.mutation<{ amount: number }, number>({ |
| 3370 |
query: (amount) => ({ |
| 3371 |
url: '', |
| 3372 |
method: 'POST', |
| 3373 |
body: { |
| 3374 |
amount, |
| 3375 |
}, |
| 3376 |
}), |
| 3377 |
}), |
| 3378 |
}), |
| 3379 |
}) |
| 3380 |
|
| 3381 |
const storeRef = setupApiStore(api, { |
| 3382 |
...actionsReducer, |
| 3383 |
}) |
| 3384 |
|
| 3385 |
it('causes no more than one rerender when using selectFromResult with an empty object', async () => { |
| 3386 |
function Counter() { |
| 3387 |
const [increment] = api.endpoints.increment.useMutation({ |
| 3388 |
selectFromResult: () => ({}), |
| 3389 |
}) |
| 3390 |
getRenderCount = useRenderCounter() |
| 3391 |
|
| 3392 |
return ( |
| 3393 |
<div> |
| 3394 |
<button |
| 3395 |
data-testid="incrementButton" |
| 3396 |
onClick={() => increment(1)} |
| 3397 |
></button> |
| 3398 |
</div> |
| 3399 |
) |
| 3400 |
} |
| 3401 |
|
| 3402 |
render(<Counter />, { wrapper: storeRef.wrapper }) |
| 3403 |
|
| 3404 |
expect(getRenderCount()).toBe(1) |
| 3405 |
|
| 3406 |
fireEvent.click(screen.getByTestId('incrementButton')) |
| 3407 |
await waitMs(200) // give our baseQuery a chance to return |
| 3408 |
expect(getRenderCount()).toBe(2) |
| 3409 |
|
| 3410 |
fireEvent.click(screen.getByTestId('incrementButton')) |
| 3411 |
await waitMs(200) |
| 3412 |
expect(getRenderCount()).toBe(3) |
| 3413 |
|
| 3414 |
const { increment } = api.endpoints |
| 3415 |
|
| 3416 |
expect(storeRef.store.getState().actions).toMatchSequence( |
| 3417 |
api.internalActions.middlewareRegistered.match, |
| 3418 |
increment.matchPending, |
| 3419 |
increment.matchFulfilled, |
| 3420 |
increment.matchPending, |
| 3421 |
api.internalActions.removeMutationResult.match, |
| 3422 |
increment.matchFulfilled, |
| 3423 |
) |
| 3424 |
}) |
| 3425 |
|
| 3426 |
it('causes rerenders when only selected data changes', async () => { |
| 3427 |
function Counter() { |
| 3428 |
const [increment, { data }] = api.endpoints.increment.useMutation({ |
| 3429 |
selectFromResult: ({ data }) => ({ data }), |
| 3430 |
}) |
| 3431 |
getRenderCount = useRenderCounter() |
| 3432 |
|
| 3433 |
return ( |
| 3434 |
<div> |
| 3435 |
<button |
| 3436 |
data-testid="incrementButton" |
| 3437 |
onClick={() => increment(1)} |
| 3438 |
></button> |
| 3439 |
<div data-testid="data">{JSON.stringify(data)}</div> |
| 3440 |
</div> |
| 3441 |
) |
| 3442 |
} |
| 3443 |
|
| 3444 |
render(<Counter />, { wrapper: storeRef.wrapper }) |
| 3445 |
|
| 3446 |
expect(getRenderCount()).toBe(1) |
| 3447 |
|
| 3448 |
fireEvent.click(screen.getByTestId('incrementButton')) |
| 3449 |
await waitFor(() => |
| 3450 |
expect(screen.getByTestId('data').textContent).toBe( |
| 3451 |
JSON.stringify({ amount: 1 }), |
| 3452 |
), |
| 3453 |
) |
| 3454 |
expect(getRenderCount()).toBe(3) |
| 3455 |
|
| 3456 |
fireEvent.click(screen.getByTestId('incrementButton')) |
| 3457 |
await waitFor(() => |
| 3458 |
expect(screen.getByTestId('data').textContent).toBe( |
| 3459 |
JSON.stringify({ amount: 2 }), |
| 3460 |
), |
| 3461 |
) |
| 3462 |
expect(getRenderCount()).toBe(5) |
| 3463 |
}) |
| 3464 |
|
| 3465 |
it('causes the expected # of rerenders when NOT using selectFromResult', async () => { |
| 3466 |
function Counter() { |
| 3467 |
const [increment, data] = api.endpoints.increment.useMutation() |
| 3468 |
getRenderCount = useRenderCounter() |
| 3469 |
|
| 3470 |
return ( |
| 3471 |
<div> |
| 3472 |
<button |
| 3473 |
data-testid="incrementButton" |
| 3474 |
onClick={() => increment(1)} |
| 3475 |
></button> |
| 3476 |
<div data-testid="status">{String(data.status)}</div> |
| 3477 |
</div> |
| 3478 |
) |
| 3479 |
} |
| 3480 |
|
| 3481 |
render(<Counter />, { wrapper: storeRef.wrapper }) |
| 3482 |
|
| 3483 |
expect(getRenderCount()).toBe(1) // mount, uninitialized status in substate |
| 3484 |
|
| 3485 |
fireEvent.click(screen.getByTestId('incrementButton')) |
| 3486 |
|
| 3487 |
expect(getRenderCount()).toBe(2) // will be pending, isLoading: true, |
| 3488 |
await waitFor(() => |
| 3489 |
expect(screen.getByTestId('status').textContent).toBe('pending'), |
| 3490 |
) |
| 3491 |
await waitFor(() => |
| 3492 |
expect(screen.getByTestId('status').textContent).toBe('fulfilled'), |
| 3493 |
) |
| 3494 |
expect(getRenderCount()).toBe(3) |
| 3495 |
|
| 3496 |
fireEvent.click(screen.getByTestId('incrementButton')) |
| 3497 |
await waitFor(() => |
| 3498 |
expect(screen.getByTestId('status').textContent).toBe('pending'), |
| 3499 |
) |
| 3500 |
await waitFor(() => |
| 3501 |
expect(screen.getByTestId('status').textContent).toBe('fulfilled'), |
| 3502 |
) |
| 3503 |
expect(getRenderCount()).toBe(5) |
| 3504 |
}) |
| 3505 |
|
| 3506 |
it('useMutation with selectFromResult option has a type error if the result is not an object', async () => { |
| 3507 |
function Counter() { |
| 3508 |
const [increment] = api.endpoints.increment.useMutation({ |
| 3509 |
// selectFromResult must always return an object |
| 3510 |
// @ts-expect-error |
| 3511 |
selectFromResult: () => 42, |
| 3512 |
}) |
| 3513 |
|
| 3514 |
return ( |
| 3515 |
<div> |
| 3516 |
<button |
| 3517 |
data-testid="incrementButton" |
| 3518 |
onClick={() => increment(1)} |
| 3519 |
></button> |
| 3520 |
</div> |
| 3521 |
) |
| 3522 |
} |
| 3523 |
|
| 3524 |
render(<Counter />, { wrapper: storeRef.wrapper }) |
| 3525 |
}) |
| 3526 |
}) |
| 3527 |
}) |
| 3528 |
|
| 3529 |
describe('skip behavior', () => { |
| 3530 |
const uninitialized = { |
| 3531 |
status: QueryStatus.uninitialized, |
| 3532 |
refetch: expect.any(Function), |
| 3533 |
data: undefined, |
| 3534 |
isError: false, |
| 3535 |
isFetching: false, |
| 3536 |
isLoading: false, |
| 3537 |
isSuccess: false, |
| 3538 |
isUninitialized: true, |
| 3539 |
} |
| 3540 |
|
| 3541 |
test('normal skip', async () => { |
| 3542 |
const { result, rerender } = renderHook( |
| 3543 |
([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) => |
| 3544 |
api.endpoints.getUser.useQuery(arg, options), |
| 3545 |
{ |
| 3546 |
wrapper: storeRef.wrapper, |
| 3547 |
initialProps: [1, { skip: true }], |
| 3548 |
}, |
| 3549 |
) |
| 3550 |
|
| 3551 |
expect(result.current).toEqual(uninitialized) |
| 3552 |
await waitMs(1) |
| 3553 |
expect(getSubscriptionCount('getUser(1)')).toBe(0) |
| 3554 |
|
| 3555 |
rerender([1]) |
| 3556 |
|
| 3557 |
await act(async () => { |
| 3558 |
await waitForFakeTimer(150) |
| 3559 |
}) |
| 3560 |
|
| 3561 |
expect(result.current).toMatchObject({ status: QueryStatus.fulfilled }) |
| 3562 |
await waitMs(1) |
| 3563 |
expect(getSubscriptionCount('getUser(1)')).toBe(1) |
| 3564 |
|
| 3565 |
rerender([1, { skip: true }]) |
| 3566 |
|
| 3567 |
expect(result.current).toEqual({ |
| 3568 |
...uninitialized, |
| 3569 |
isSuccess: true, |
| 3570 |
currentData: undefined, |
| 3571 |
data: { name: 'Timmy' }, |
| 3572 |
}) |
| 3573 |
await waitMs(1) |
| 3574 |
expect(getSubscriptionCount('getUser(1)')).toBe(0) |
| 3575 |
}) |
| 3576 |
|
| 3577 |
test('skipToken', async () => { |
| 3578 |
const { result, rerender } = renderHook( |
| 3579 |
([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) => |
| 3580 |
api.endpoints.getUser.useQuery(arg, options), |
| 3581 |
{ |
| 3582 |
wrapper: storeRef.wrapper, |
| 3583 |
initialProps: [skipToken], |
| 3584 |
}, |
| 3585 |
) |
| 3586 |
|
| 3587 |
expect(result.current).toEqual(uninitialized) |
| 3588 |
await waitMs(1) |
| 3589 |
|
| 3590 |
expect(getSubscriptionCount('getUser(1)')).toBe(0) |
| 3591 |
// also no subscription on `getUser(skipToken)` or similar: |
| 3592 |
expect(getSubscriptions()).toEqual({}) |
| 3593 |
|
| 3594 |
rerender([1]) |
| 3595 |
|
| 3596 |
await act(async () => { |
| 3597 |
await waitForFakeTimer(150) |
| 3598 |
}) |
| 3599 |
|
| 3600 |
expect(result.current).toMatchObject({ status: QueryStatus.fulfilled }) |
| 3601 |
await waitMs(1) |
| 3602 |
expect(getSubscriptionCount('getUser(1)')).toBe(1) |
| 3603 |
expect(getSubscriptions()).not.toEqual({}) |
| 3604 |
|
| 3605 |
rerender([skipToken]) |
| 3606 |
|
| 3607 |
expect(result.current).toEqual({ |
| 3608 |
...uninitialized, |
| 3609 |
isSuccess: true, |
| 3610 |
currentData: undefined, |
| 3611 |
data: { name: 'Timmy' }, |
| 3612 |
}) |
| 3613 |
await waitMs(1) |
| 3614 |
expect(getSubscriptionCount('getUser(1)')).toBe(0) |
| 3615 |
}) |
| 3616 |
|
| 3617 |
test('skipToken does not break serializeQueryArgs', async () => { |
| 3618 |
const { result, rerender } = renderHook( |
| 3619 |
([arg, options]: Parameters< |
| 3620 |
typeof api.endpoints.queryWithDeepArg.useQuery |
| 3621 |
>) => api.endpoints.queryWithDeepArg.useQuery(arg, options), |
| 3622 |
{ |
| 3623 |
wrapper: storeRef.wrapper, |
| 3624 |
initialProps: [skipToken], |
| 3625 |
}, |
| 3626 |
) |
| 3627 |
|
| 3628 |
expect(result.current).toEqual(uninitialized) |
| 3629 |
await waitMs(1) |
| 3630 |
|
| 3631 |
expect(getSubscriptionCount('nestedValue')).toBe(0) |
| 3632 |
// also no subscription on `getUser(skipToken)` or similar: |
| 3633 |
expect(getSubscriptions()).toEqual({}) |
| 3634 |
|
| 3635 |
rerender([{ param: { nested: 'nestedValue' } }]) |
| 3636 |
|
| 3637 |
await act(async () => { |
| 3638 |
await waitForFakeTimer(150) |
| 3639 |
}) |
| 3640 |
|
| 3641 |
expect(result.current).toMatchObject({ status: QueryStatus.fulfilled }) |
| 3642 |
await waitMs(1) |
| 3643 |
|
| 3644 |
expect(getSubscriptionCount('nestedValue')).toBe(1) |
| 3645 |
expect(getSubscriptions()).not.toEqual({}) |
| 3646 |
|
| 3647 |
rerender([skipToken]) |
| 3648 |
|
| 3649 |
expect(result.current).toEqual({ |
| 3650 |
...uninitialized, |
| 3651 |
isSuccess: true, |
| 3652 |
currentData: undefined, |
| 3653 |
data: {}, |
| 3654 |
}) |
| 3655 |
await waitMs(1) |
| 3656 |
expect(getSubscriptionCount('nestedValue')).toBe(0) |
| 3657 |
}) |
| 3658 |
|
| 3659 |
test('skipping a previously fetched query retains the existing value as `data`, but clears `currentData`', async () => { |
| 3660 |
const { result, rerender } = renderHook( |
| 3661 |
([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) => |
| 3662 |
api.endpoints.getUser.useQuery(arg, options), |
| 3663 |
{ |
| 3664 |
wrapper: storeRef.wrapper, |
| 3665 |
initialProps: [1], |
| 3666 |
}, |
| 3667 |
) |
| 3668 |
|
| 3669 |
await act(async () => { |
| 3670 |
await waitForFakeTimer(150) |
| 3671 |
}) |
| 3672 |
|
| 3673 |
// Normal fulfilled result, with both `data` and `currentData` |
| 3674 |
expect(result.current).toMatchObject({ |
| 3675 |
status: QueryStatus.fulfilled, |
| 3676 |
isSuccess: true, |
| 3677 |
data: { name: 'Timmy' }, |
| 3678 |
currentData: { name: 'Timmy' }, |
| 3679 |
}) |
| 3680 |
|
| 3681 |
rerender([1, { skip: true }]) |
| 3682 |
|
| 3683 |
// After skipping, the query is "uninitialized", but still retains the last fetched `data` |
| 3684 |
// even though it's skipped. `currentData` is undefined, since that matches the current arg. |
| 3685 |
expect(result.current).toMatchObject({ |
| 3686 |
status: QueryStatus.uninitialized, |
| 3687 |
isSuccess: true, |
| 3688 |
data: { name: 'Timmy' }, |
| 3689 |
currentData: undefined, |
| 3690 |
}) |
| 3691 |
}) |
| 3692 |
}) |