| 1 |
import { noop } from '@internal/listenerMiddleware/utils' |
| 2 |
import { server } from '@internal/query/tests/mocks/server' |
| 3 |
import { |
| 4 |
getSerializedHeaders, |
| 5 |
setupApiStore, |
| 6 |
} from '@internal/tests/utils/helpers' |
| 7 |
import { configureStore, createAction, createReducer } from '@reduxjs/toolkit' |
| 8 |
import type { |
| 9 |
DefinitionsFromApi, |
| 10 |
FetchBaseQueryMeta, |
| 11 |
OverrideResultType, |
| 12 |
SerializeQueryArgs, |
| 13 |
TagTypesFromApi, |
| 14 |
} from '@reduxjs/toolkit/query' |
| 15 |
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query' |
| 16 |
import { HttpResponse, delay, http } from 'msw' |
| 17 |
import nodeFetch from 'node-fetch' |
| 18 |
|
| 19 |
beforeAll(() => { |
| 20 |
vi.stubEnv('NODE_ENV', 'development') |
| 21 |
|
| 22 |
return vi.unstubAllEnvs |
| 23 |
}) |
| 24 |
|
| 25 |
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop) |
| 26 |
|
| 27 |
afterEach(() => { |
| 28 |
vi.clearAllMocks() |
| 29 |
}) |
| 30 |
|
| 31 |
afterAll(() => { |
| 32 |
vi.restoreAllMocks() |
| 33 |
}) |
| 34 |
|
| 35 |
function paginate<T>(array: T[], page_size: number, page_number: number) { |
| 36 |
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument |
| 37 |
return array.slice((page_number - 1) * page_size, page_number * page_size) |
| 38 |
} |
| 39 |
|
| 40 |
test('sensible defaults', () => { |
| 41 |
const api = createApi({ |
| 42 |
baseQuery: fetchBaseQuery(), |
| 43 |
endpoints: (build) => ({ |
| 44 |
getUser: build.query<unknown, void>({ |
| 45 |
query(id) { |
| 46 |
return { url: `user/${id}` } |
| 47 |
}, |
| 48 |
}), |
| 49 |
updateUser: build.mutation<unknown, void>({ |
| 50 |
query: () => '', |
| 51 |
}), |
| 52 |
}), |
| 53 |
}) |
| 54 |
configureStore({ |
| 55 |
reducer: { |
| 56 |
[api.reducerPath]: api.reducer, |
| 57 |
}, |
| 58 |
middleware: (gDM) => gDM().concat(api.middleware), |
| 59 |
}) |
| 60 |
expect(api.reducerPath).toBe('api') |
| 61 |
|
| 62 |
expect(api.endpoints.getUser.name).toBe('getUser') |
| 63 |
expect(api.endpoints.updateUser.name).toBe('updateUser') |
| 64 |
}) |
| 65 |
|
| 66 |
describe('wrong tagTypes log errors', () => { |
| 67 |
const baseQuery = vi.fn() |
| 68 |
const api = createApi({ |
| 69 |
baseQuery, |
| 70 |
tagTypes: ['User'], |
| 71 |
endpoints: (build) => ({ |
| 72 |
provideNothing: build.query<unknown, void>({ |
| 73 |
query: () => '', |
| 74 |
}), |
| 75 |
provideTypeString: build.query<unknown, void>({ |
| 76 |
query: () => '', |
| 77 |
providesTags: ['User'], |
| 78 |
}), |
| 79 |
provideTypeWithId: build.query<unknown, void>({ |
| 80 |
query: () => '', |
| 81 |
providesTags: [{ type: 'User', id: 5 }], |
| 82 |
}), |
| 83 |
provideTypeWithIdAndCallback: build.query<unknown, void>({ |
| 84 |
query: () => '', |
| 85 |
providesTags: () => [{ type: 'User', id: 5 }], |
| 86 |
}), |
| 87 |
provideWrongTypeString: build.query<unknown, void>({ |
| 88 |
query: () => '', |
| 89 |
// @ts-expect-error |
| 90 |
providesTags: ['Users'], |
| 91 |
}), |
| 92 |
provideWrongTypeWithId: build.query<unknown, void>({ |
| 93 |
query: () => '', |
| 94 |
// @ts-expect-error |
| 95 |
providesTags: [{ type: 'Users', id: 5 }], |
| 96 |
}), |
| 97 |
provideWrongTypeWithIdAndCallback: build.query<unknown, void>({ |
| 98 |
query: () => '', |
| 99 |
// @ts-expect-error |
| 100 |
providesTags: () => [{ type: 'Users', id: 5 }], |
| 101 |
}), |
| 102 |
invalidateNothing: build.query<unknown, void>({ |
| 103 |
query: () => '', |
| 104 |
}), |
| 105 |
invalidateTypeString: build.mutation<unknown, void>({ |
| 106 |
query: () => '', |
| 107 |
invalidatesTags: ['User'], |
| 108 |
}), |
| 109 |
invalidateTypeWithId: build.mutation<unknown, void>({ |
| 110 |
query: () => '', |
| 111 |
invalidatesTags: [{ type: 'User', id: 5 }], |
| 112 |
}), |
| 113 |
invalidateTypeWithIdAndCallback: build.mutation<unknown, void>({ |
| 114 |
query: () => '', |
| 115 |
invalidatesTags: () => [{ type: 'User', id: 5 }], |
| 116 |
}), |
| 117 |
|
| 118 |
invalidateWrongTypeString: build.mutation<unknown, void>({ |
| 119 |
query: () => '', |
| 120 |
// @ts-expect-error |
| 121 |
invalidatesTags: ['Users'], |
| 122 |
}), |
| 123 |
invalidateWrongTypeWithId: build.mutation<unknown, void>({ |
| 124 |
query: () => '', |
| 125 |
// @ts-expect-error |
| 126 |
invalidatesTags: [{ type: 'Users', id: 5 }], |
| 127 |
}), |
| 128 |
invalidateWrongTypeWithIdAndCallback: build.mutation<unknown, void>({ |
| 129 |
query: () => '', |
| 130 |
// @ts-expect-error |
| 131 |
invalidatesTags: () => [{ type: 'Users', id: 5 }], |
| 132 |
}), |
| 133 |
}), |
| 134 |
}) |
| 135 |
const store = configureStore({ |
| 136 |
reducer: { |
| 137 |
[api.reducerPath]: api.reducer, |
| 138 |
}, |
| 139 |
middleware: (gDM) => gDM().concat(api.middleware), |
| 140 |
}) |
| 141 |
|
| 142 |
beforeEach(() => { |
| 143 |
baseQuery.mockResolvedValue({ data: 'foo' }) |
| 144 |
}) |
| 145 |
|
| 146 |
test.each<[keyof typeof api.endpoints, boolean?]>([ |
| 147 |
['provideNothing', false], |
| 148 |
['provideTypeString', false], |
| 149 |
['provideTypeWithId', false], |
| 150 |
['provideTypeWithIdAndCallback', false], |
| 151 |
['provideWrongTypeString', true], |
| 152 |
['provideWrongTypeWithId', true], |
| 153 |
['provideWrongTypeWithIdAndCallback', true], |
| 154 |
['invalidateNothing', false], |
| 155 |
['invalidateTypeString', false], |
| 156 |
['invalidateTypeWithId', false], |
| 157 |
['invalidateTypeWithIdAndCallback', false], |
| 158 |
['invalidateWrongTypeString', true], |
| 159 |
['invalidateWrongTypeWithId', true], |
| 160 |
['invalidateWrongTypeWithIdAndCallback', true], |
| 161 |
])(`endpoint %s should log an error? %s`, async (endpoint, shouldError) => { |
| 162 |
vi.stubEnv('NODE_ENV', 'development') |
| 163 |
|
| 164 |
// @ts-ignore |
| 165 |
store.dispatch(api.endpoints[endpoint].initiate()) |
| 166 |
let result: { status: string } |
| 167 |
do { |
| 168 |
await delay(5) |
| 169 |
// @ts-ignore |
| 170 |
result = api.endpoints[endpoint].select()(store.getState()) |
| 171 |
} while (result.status === 'pending') |
| 172 |
|
| 173 |
if (shouldError) { |
| 174 |
expect(consoleErrorSpy).toHaveBeenLastCalledWith( |
| 175 |
"Tag type 'Users' was used, but not specified in `tagTypes`!", |
| 176 |
) |
| 177 |
} else { |
| 178 |
expect(consoleErrorSpy).not.toHaveBeenCalled() |
| 179 |
} |
| 180 |
}) |
| 181 |
}) |
| 182 |
|
| 183 |
describe('endpoint definition typings', () => { |
| 184 |
const api = createApi({ |
| 185 |
baseQuery: (from: 'From'): { data: 'To' } | Promise<{ data: 'To' }> => ({ |
| 186 |
data: 'To', |
| 187 |
}), |
| 188 |
endpoints: () => ({}), |
| 189 |
tagTypes: ['typeA', 'typeB'], |
| 190 |
}) |
| 191 |
test('query: query & transformResponse types', () => { |
| 192 |
api.injectEndpoints({ |
| 193 |
endpoints: (build) => ({ |
| 194 |
query: build.query<'RetVal', 'Arg'>({ |
| 195 |
query: (x: 'Arg') => 'From' as const, |
| 196 |
transformResponse(r: 'To') { |
| 197 |
return 'RetVal' as const |
| 198 |
}, |
| 199 |
}), |
| 200 |
query1: build.query<'RetVal', 'Arg'>({ |
| 201 |
// @ts-expect-error |
| 202 |
query: (x: 'Error') => 'From' as const, |
| 203 |
transformResponse(r: 'To') { |
| 204 |
return 'RetVal' as const |
| 205 |
}, |
| 206 |
}), |
| 207 |
query2: build.query<'RetVal', 'Arg'>({ |
| 208 |
// @ts-expect-error |
| 209 |
query: (x: 'Arg') => 'Error' as const, |
| 210 |
transformResponse(r: 'To') { |
| 211 |
return 'RetVal' as const |
| 212 |
}, |
| 213 |
}), |
| 214 |
query3: build.query<'RetVal', 'Arg'>({ |
| 215 |
query: (x: 'Arg') => 'From' as const, |
| 216 |
// @ts-expect-error |
| 217 |
transformResponse(r: 'Error') { |
| 218 |
return 'RetVal' as const |
| 219 |
}, |
| 220 |
}), |
| 221 |
query4: build.query<'RetVal', 'Arg'>({ |
| 222 |
query: (x: 'Arg') => 'From' as const, |
| 223 |
// @ts-expect-error |
| 224 |
transformResponse(r: 'To') { |
| 225 |
return 'Error' as const |
| 226 |
}, |
| 227 |
}), |
| 228 |
queryInference1: build.query<'RetVal', 'Arg'>({ |
| 229 |
query: (x) => { |
| 230 |
return 'From' |
| 231 |
}, |
| 232 |
transformResponse(r) { |
| 233 |
return 'RetVal' |
| 234 |
}, |
| 235 |
}), |
| 236 |
queryInference2: (() => { |
| 237 |
const query = build.query({ |
| 238 |
query: (x: 'Arg') => 'From' as const, |
| 239 |
transformResponse(r: 'To') { |
| 240 |
return 'RetVal' as const |
| 241 |
}, |
| 242 |
}) |
| 243 |
return query |
| 244 |
})(), |
| 245 |
}), |
| 246 |
}) |
| 247 |
}) |
| 248 |
test('mutation: query & transformResponse types', () => { |
| 249 |
api.injectEndpoints({ |
| 250 |
endpoints: (build) => ({ |
| 251 |
query: build.mutation<'RetVal', 'Arg'>({ |
| 252 |
query: (x: 'Arg') => 'From' as const, |
| 253 |
transformResponse(r: 'To') { |
| 254 |
return 'RetVal' as const |
| 255 |
}, |
| 256 |
}), |
| 257 |
query1: build.mutation<'RetVal', 'Arg'>({ |
| 258 |
// @ts-expect-error |
| 259 |
query: (x: 'Error') => 'From' as const, |
| 260 |
transformResponse(r: 'To') { |
| 261 |
return 'RetVal' as const |
| 262 |
}, |
| 263 |
}), |
| 264 |
query2: build.mutation<'RetVal', 'Arg'>({ |
| 265 |
// @ts-expect-error |
| 266 |
query: (x: 'Arg') => 'Error' as const, |
| 267 |
transformResponse(r: 'To') { |
| 268 |
return 'RetVal' as const |
| 269 |
}, |
| 270 |
}), |
| 271 |
query3: build.mutation<'RetVal', 'Arg'>({ |
| 272 |
query: (x: 'Arg') => 'From' as const, |
| 273 |
// @ts-expect-error |
| 274 |
transformResponse(r: 'Error') { |
| 275 |
return 'RetVal' as const |
| 276 |
}, |
| 277 |
}), |
| 278 |
query4: build.mutation<'RetVal', 'Arg'>({ |
| 279 |
query: (x: 'Arg') => 'From' as const, |
| 280 |
// @ts-expect-error |
| 281 |
transformResponse(r: 'To') { |
| 282 |
return 'Error' as const |
| 283 |
}, |
| 284 |
}), |
| 285 |
mutationInference1: build.mutation<'RetVal', 'Arg'>({ |
| 286 |
query: (x) => { |
| 287 |
return 'From' |
| 288 |
}, |
| 289 |
transformResponse(r) { |
| 290 |
return 'RetVal' |
| 291 |
}, |
| 292 |
}), |
| 293 |
mutationInference2: (() => { |
| 294 |
const query = build.mutation({ |
| 295 |
query: (x: 'Arg') => 'From' as const, |
| 296 |
transformResponse(r: 'To') { |
| 297 |
return 'RetVal' as const |
| 298 |
}, |
| 299 |
}) |
| 300 |
return query |
| 301 |
})(), |
| 302 |
}), |
| 303 |
}) |
| 304 |
}) |
| 305 |
|
| 306 |
describe('enhancing endpoint definitions', () => { |
| 307 |
const baseQuery = vi.fn((x: string) => ({ data: 'success' })) |
| 308 |
const commonBaseQueryApi = { |
| 309 |
dispatch: expect.any(Function), |
| 310 |
endpoint: expect.any(String), |
| 311 |
abort: expect.any(Function), |
| 312 |
extra: undefined, |
| 313 |
forced: expect.any(Boolean), |
| 314 |
getState: expect.any(Function), |
| 315 |
signal: expect.any(Object), |
| 316 |
type: expect.any(String), |
| 317 |
queryCacheKey: expect.any(String), |
| 318 |
} |
| 319 |
beforeEach(() => { |
| 320 |
baseQuery.mockClear() |
| 321 |
}) |
| 322 |
function getNewApi() { |
| 323 |
return createApi({ |
| 324 |
baseQuery, |
| 325 |
tagTypes: ['old'], |
| 326 |
endpoints: (build) => ({ |
| 327 |
query1: build.query<'out1', 'in1'>({ query: (id) => `${id}` }), |
| 328 |
query2: build.query<'out2', 'in2'>({ query: (id) => `${id}` }), |
| 329 |
mutation1: build.mutation<'out1', 'in1'>({ query: (id) => `${id}` }), |
| 330 |
mutation2: build.mutation<'out2', 'in2'>({ query: (id) => `${id}` }), |
| 331 |
}), |
| 332 |
}) |
| 333 |
} |
| 334 |
let api = getNewApi() |
| 335 |
beforeEach(() => { |
| 336 |
api = getNewApi() |
| 337 |
}) |
| 338 |
|
| 339 |
test('pre-modification behavior', async () => { |
| 340 |
const storeRef = setupApiStore(api, undefined, { |
| 341 |
withoutTestLifecycles: true, |
| 342 |
}) |
| 343 |
storeRef.store.dispatch(api.endpoints.query1.initiate('in1')) |
| 344 |
storeRef.store.dispatch(api.endpoints.query2.initiate('in2')) |
| 345 |
storeRef.store.dispatch(api.endpoints.mutation1.initiate('in1')) |
| 346 |
storeRef.store.dispatch(api.endpoints.mutation2.initiate('in2')) |
| 347 |
|
| 348 |
expect(baseQuery.mock.calls).toEqual([ |
| 349 |
[ |
| 350 |
'in1', |
| 351 |
{ |
| 352 |
dispatch: expect.any(Function), |
| 353 |
endpoint: expect.any(String), |
| 354 |
getState: expect.any(Function), |
| 355 |
signal: expect.any(Object), |
| 356 |
abort: expect.any(Function), |
| 357 |
forced: expect.any(Boolean), |
| 358 |
type: expect.any(String), |
| 359 |
queryCacheKey: expect.any(String), |
| 360 |
}, |
| 361 |
undefined, |
| 362 |
], |
| 363 |
[ |
| 364 |
'in2', |
| 365 |
{ |
| 366 |
dispatch: expect.any(Function), |
| 367 |
endpoint: expect.any(String), |
| 368 |
getState: expect.any(Function), |
| 369 |
signal: expect.any(Object), |
| 370 |
abort: expect.any(Function), |
| 371 |
forced: expect.any(Boolean), |
| 372 |
type: expect.any(String), |
| 373 |
queryCacheKey: expect.any(String), |
| 374 |
}, |
| 375 |
undefined, |
| 376 |
], |
| 377 |
[ |
| 378 |
'in1', |
| 379 |
{ |
| 380 |
dispatch: expect.any(Function), |
| 381 |
endpoint: expect.any(String), |
| 382 |
getState: expect.any(Function), |
| 383 |
signal: expect.any(Object), |
| 384 |
abort: expect.any(Function), |
| 385 |
// forced: undefined, |
| 386 |
type: expect.any(String), |
| 387 |
}, |
| 388 |
undefined, |
| 389 |
], |
| 390 |
[ |
| 391 |
'in2', |
| 392 |
{ |
| 393 |
dispatch: expect.any(Function), |
| 394 |
endpoint: expect.any(String), |
| 395 |
getState: expect.any(Function), |
| 396 |
signal: expect.any(Object), |
| 397 |
abort: expect.any(Function), |
| 398 |
// forced: undefined, |
| 399 |
type: expect.any(String), |
| 400 |
}, |
| 401 |
undefined, |
| 402 |
], |
| 403 |
]) |
| 404 |
}) |
| 405 |
|
| 406 |
test('warn on wrong tagType', async () => { |
| 407 |
vi.stubEnv('NODE_ENV', 'development') |
| 408 |
|
| 409 |
const storeRef = setupApiStore(api, undefined, { |
| 410 |
withoutTestLifecycles: true, |
| 411 |
}) |
| 412 |
// only type-test this part |
| 413 |
if (2 > 1) { |
| 414 |
api.enhanceEndpoints({ |
| 415 |
endpoints: { |
| 416 |
query1: { |
| 417 |
// @ts-expect-error |
| 418 |
providesTags: ['new'], |
| 419 |
}, |
| 420 |
query2: { |
| 421 |
// @ts-expect-error |
| 422 |
providesTags: ['missing'], |
| 423 |
}, |
| 424 |
}, |
| 425 |
}) |
| 426 |
} |
| 427 |
|
| 428 |
const enhanced = api.enhanceEndpoints({ |
| 429 |
addTagTypes: ['new'], |
| 430 |
endpoints: { |
| 431 |
query1: { |
| 432 |
providesTags: ['new'], |
| 433 |
}, |
| 434 |
query2: { |
| 435 |
// @ts-expect-error |
| 436 |
providesTags: ['missing'], |
| 437 |
}, |
| 438 |
}, |
| 439 |
}) |
| 440 |
|
| 441 |
storeRef.store.dispatch(api.endpoints.query1.initiate('in1')) |
| 442 |
await delay(1) |
| 443 |
expect(consoleErrorSpy).not.toHaveBeenCalled() |
| 444 |
|
| 445 |
storeRef.store.dispatch(api.endpoints.query2.initiate('in2')) |
| 446 |
await delay(1) |
| 447 |
|
| 448 |
expect(consoleErrorSpy).toHaveBeenCalledOnce() |
| 449 |
|
| 450 |
expect(consoleErrorSpy).toHaveBeenLastCalledWith( |
| 451 |
"Tag type 'missing' was used, but not specified in `tagTypes`!", |
| 452 |
) |
| 453 |
|
| 454 |
// only type-test this part |
| 455 |
if (2 > 1) { |
| 456 |
enhanced.enhanceEndpoints({ |
| 457 |
endpoints: { |
| 458 |
query1: { |
| 459 |
// returned `enhanced` api contains "new" enitityType |
| 460 |
providesTags: ['new'], |
| 461 |
}, |
| 462 |
query2: { |
| 463 |
// @ts-expect-error |
| 464 |
providesTags: ['missing'], |
| 465 |
}, |
| 466 |
}, |
| 467 |
}) |
| 468 |
} |
| 469 |
}) |
| 470 |
|
| 471 |
test('modify', () => { |
| 472 |
const storeRef = setupApiStore(api, undefined, { |
| 473 |
withoutTestLifecycles: true, |
| 474 |
}) |
| 475 |
api.enhanceEndpoints({ |
| 476 |
endpoints: { |
| 477 |
query1: { |
| 478 |
query: (x) => { |
| 479 |
return 'modified1' |
| 480 |
}, |
| 481 |
}, |
| 482 |
query2(definition) { |
| 483 |
definition.query = (x) => { |
| 484 |
return 'modified2' |
| 485 |
} |
| 486 |
}, |
| 487 |
mutation1: { |
| 488 |
query: (x) => { |
| 489 |
return 'modified1' |
| 490 |
}, |
| 491 |
}, |
| 492 |
mutation2(definition) { |
| 493 |
definition.query = (x) => { |
| 494 |
return 'modified2' |
| 495 |
} |
| 496 |
}, |
| 497 |
// @ts-expect-error |
| 498 |
nonExisting: {}, |
| 499 |
}, |
| 500 |
}) |
| 501 |
|
| 502 |
storeRef.store.dispatch(api.endpoints.query1.initiate('in1')) |
| 503 |
storeRef.store.dispatch(api.endpoints.query2.initiate('in2')) |
| 504 |
storeRef.store.dispatch(api.endpoints.mutation1.initiate('in1')) |
| 505 |
storeRef.store.dispatch(api.endpoints.mutation2.initiate('in2')) |
| 506 |
|
| 507 |
expect(baseQuery.mock.calls).toEqual([ |
| 508 |
['modified1', commonBaseQueryApi, undefined], |
| 509 |
['modified2', commonBaseQueryApi, undefined], |
| 510 |
[ |
| 511 |
'modified1', |
| 512 |
{ |
| 513 |
...commonBaseQueryApi, |
| 514 |
forced: undefined, |
| 515 |
queryCacheKey: undefined, |
| 516 |
}, |
| 517 |
undefined, |
| 518 |
], |
| 519 |
[ |
| 520 |
'modified2', |
| 521 |
{ |
| 522 |
...commonBaseQueryApi, |
| 523 |
forced: undefined, |
| 524 |
queryCacheKey: undefined, |
| 525 |
}, |
| 526 |
undefined, |
| 527 |
], |
| 528 |
]) |
| 529 |
}) |
| 530 |
|
| 531 |
test('updated transform response types', async () => { |
| 532 |
const baseApi = createApi({ |
| 533 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }), |
| 534 |
tagTypes: ['old'], |
| 535 |
endpoints: (build) => ({ |
| 536 |
query1: build.query<'out1', void>({ query: () => 'success' }), |
| 537 |
mutation1: build.mutation<'out1', void>({ query: () => 'success' }), |
| 538 |
}), |
| 539 |
}) |
| 540 |
|
| 541 |
type Transformed = { value: string } |
| 542 |
|
| 543 |
type Definitions = DefinitionsFromApi<typeof api> |
| 544 |
type TagTypes = TagTypesFromApi<typeof api> |
| 545 |
|
| 546 |
type Q1Definition = OverrideResultType<Definitions['query1'], Transformed> |
| 547 |
type M1Definition = OverrideResultType< |
| 548 |
Definitions['mutation1'], |
| 549 |
Transformed |
| 550 |
> |
| 551 |
|
| 552 |
type UpdatedDefitions = Omit<Definitions, 'query1' | 'mutation1'> & { |
| 553 |
query1: Q1Definition |
| 554 |
mutation1: M1Definition |
| 555 |
} |
| 556 |
|
| 557 |
const enhancedApi = baseApi.enhanceEndpoints<TagTypes, UpdatedDefitions>({ |
| 558 |
endpoints: { |
| 559 |
query1: { |
| 560 |
transformResponse: (a, b, c) => ({ |
| 561 |
value: 'transformed', |
| 562 |
}), |
| 563 |
}, |
| 564 |
mutation1: { |
| 565 |
transformResponse: (a, b, c) => ({ |
| 566 |
value: 'transformed', |
| 567 |
}), |
| 568 |
}, |
| 569 |
}, |
| 570 |
}) |
| 571 |
|
| 572 |
const storeRef = setupApiStore(enhancedApi, undefined, { |
| 573 |
withoutTestLifecycles: true, |
| 574 |
}) |
| 575 |
|
| 576 |
const queryResponse = await storeRef.store.dispatch( |
| 577 |
enhancedApi.endpoints.query1.initiate(), |
| 578 |
) |
| 579 |
expect(queryResponse.data).toEqual({ value: 'transformed' }) |
| 580 |
|
| 581 |
const mutationResponse = await storeRef.store.dispatch( |
| 582 |
enhancedApi.endpoints.mutation1.initiate(), |
| 583 |
) |
| 584 |
expect('data' in mutationResponse && mutationResponse.data).toEqual({ |
| 585 |
value: 'transformed', |
| 586 |
}) |
| 587 |
}) |
| 588 |
}) |
| 589 |
}) |
| 590 |
|
| 591 |
describe('additional transformResponse behaviors', () => { |
| 592 |
type SuccessResponse = { value: 'success' } |
| 593 |
type EchoResponseData = { banana: 'bread' } |
| 594 |
type ErrorResponse = { value: 'error' } |
| 595 |
const api = createApi({ |
| 596 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }), |
| 597 |
endpoints: (build) => ({ |
| 598 |
echo: build.mutation({ |
| 599 |
query: () => ({ method: 'PUT', url: '/echo' }), |
| 600 |
}), |
| 601 |
mutation: build.mutation({ |
| 602 |
query: () => ({ |
| 603 |
url: '/echo', |
| 604 |
method: 'POST', |
| 605 |
body: { nested: { banana: 'bread' } }, |
| 606 |
}), |
| 607 |
transformResponse: (response: { body: { nested: EchoResponseData } }) => |
| 608 |
response.body.nested, |
| 609 |
}), |
| 610 |
mutationWithError: build.mutation({ |
| 611 |
query: () => ({ |
| 612 |
url: '/error', |
| 613 |
method: 'POST', |
| 614 |
}), |
| 615 |
transformErrorResponse: (response) => { |
| 616 |
const data = response.data as ErrorResponse |
| 617 |
return data.value |
| 618 |
}, |
| 619 |
}), |
| 620 |
mutationWithMeta: build.mutation({ |
| 621 |
query: () => ({ |
| 622 |
url: '/echo', |
| 623 |
method: 'POST', |
| 624 |
body: { nested: { banana: 'bread' } }, |
| 625 |
}), |
| 626 |
transformResponse: ( |
| 627 |
response: { body: { nested: EchoResponseData } }, |
| 628 |
meta, |
| 629 |
) => { |
| 630 |
return { |
| 631 |
...response.body.nested, |
| 632 |
meta: { |
| 633 |
request: { headers: getSerializedHeaders(meta?.request.headers) }, |
| 634 |
response: { |
| 635 |
headers: getSerializedHeaders(meta?.response?.headers), |
| 636 |
}, |
| 637 |
}, |
| 638 |
} |
| 639 |
}, |
| 640 |
}), |
| 641 |
query: build.query<SuccessResponse & EchoResponseData, void>({ |
| 642 |
query: () => '/success', |
| 643 |
transformResponse: async (response: SuccessResponse) => { |
| 644 |
const res: any = await nodeFetch('https://example.com/echo', { |
| 645 |
method: 'POST', |
| 646 |
body: JSON.stringify({ banana: 'bread' }), |
| 647 |
}).then((res) => res.json()) |
| 648 |
|
| 649 |
const additionalData = res.body as EchoResponseData |
| 650 |
return { ...response, ...additionalData } |
| 651 |
}, |
| 652 |
}), |
| 653 |
queryWithMeta: build.query<SuccessResponse, void>({ |
| 654 |
query: () => '/success', |
| 655 |
transformResponse: async (response: SuccessResponse, meta) => { |
| 656 |
return { |
| 657 |
...response, |
| 658 |
meta: { |
| 659 |
request: { headers: getSerializedHeaders(meta?.request.headers) }, |
| 660 |
response: { |
| 661 |
headers: getSerializedHeaders(meta?.response?.headers), |
| 662 |
}, |
| 663 |
}, |
| 664 |
} |
| 665 |
}, |
| 666 |
}), |
| 667 |
}), |
| 668 |
}) |
| 669 |
|
| 670 |
const storeRef = setupApiStore(api) |
| 671 |
|
| 672 |
test('transformResponse handles an async transformation and returns the merged data (query)', async () => { |
| 673 |
const result = await storeRef.store.dispatch(api.endpoints.query.initiate()) |
| 674 |
|
| 675 |
expect(result.data).toEqual({ value: 'success', banana: 'bread' }) |
| 676 |
}) |
| 677 |
|
| 678 |
test('transformResponse transforms a response from a mutation', async () => { |
| 679 |
const result = await storeRef.store.dispatch( |
| 680 |
api.endpoints.mutation.initiate({}), |
| 681 |
) |
| 682 |
|
| 683 |
expect('data' in result && result.data).toEqual({ banana: 'bread' }) |
| 684 |
}) |
| 685 |
|
| 686 |
test('transformResponse transforms a response from a mutation with an error', async () => { |
| 687 |
const result = await storeRef.store.dispatch( |
| 688 |
api.endpoints.mutationWithError.initiate({}), |
| 689 |
) |
| 690 |
|
| 691 |
expect('error' in result && result.error).toEqual('error') |
| 692 |
}) |
| 693 |
|
| 694 |
test('transformResponse can inject baseQuery meta into the end result from a mutation', async () => { |
| 695 |
const result = await storeRef.store.dispatch( |
| 696 |
api.endpoints.mutationWithMeta.initiate({}), |
| 697 |
) |
| 698 |
|
| 699 |
expect('data' in result && result.data).toEqual({ |
| 700 |
banana: 'bread', |
| 701 |
meta: { |
| 702 |
request: { |
| 703 |
headers: { |
| 704 |
'content-type': 'application/json', |
| 705 |
}, |
| 706 |
}, |
| 707 |
response: { |
| 708 |
headers: { |
| 709 |
'content-type': 'application/json', |
| 710 |
}, |
| 711 |
}, |
| 712 |
}, |
| 713 |
}) |
| 714 |
}) |
| 715 |
|
| 716 |
test('transformResponse can inject baseQuery meta into the end result from a query', async () => { |
| 717 |
const result = await storeRef.store.dispatch( |
| 718 |
api.endpoints.queryWithMeta.initiate(), |
| 719 |
) |
| 720 |
|
| 721 |
expect(result.data).toEqual({ |
| 722 |
value: 'success', |
| 723 |
meta: { |
| 724 |
request: { |
| 725 |
headers: {}, |
| 726 |
}, |
| 727 |
response: { |
| 728 |
headers: { |
| 729 |
'content-type': 'application/json', |
| 730 |
}, |
| 731 |
}, |
| 732 |
}, |
| 733 |
}) |
| 734 |
}) |
| 735 |
}) |
| 736 |
|
| 737 |
describe('query endpoint lifecycles - onStart, onSuccess, onError', () => { |
| 738 |
const initialState = { |
| 739 |
count: null as null | number, |
| 740 |
} |
| 741 |
const setCount = createAction<number>('setCount') |
| 742 |
const testReducer = createReducer(initialState, (builder) => { |
| 743 |
builder.addCase(setCount, (state, action) => { |
| 744 |
state.count = action.payload |
| 745 |
}) |
| 746 |
}) |
| 747 |
|
| 748 |
type SuccessResponse = { value: 'success' } |
| 749 |
const api = createApi({ |
| 750 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }), |
| 751 |
endpoints: (build) => ({ |
| 752 |
echo: build.mutation({ |
| 753 |
query: () => ({ method: 'PUT', url: '/echo' }), |
| 754 |
}), |
| 755 |
query: build.query<SuccessResponse, void>({ |
| 756 |
query: () => '/success', |
| 757 |
async onQueryStarted(_, api) { |
| 758 |
api.dispatch(setCount(0)) |
| 759 |
try { |
| 760 |
await api.queryFulfilled |
| 761 |
api.dispatch(setCount(1)) |
| 762 |
} catch { |
| 763 |
api.dispatch(setCount(-1)) |
| 764 |
} |
| 765 |
}, |
| 766 |
}), |
| 767 |
mutation: build.mutation<SuccessResponse, void>({ |
| 768 |
query: () => ({ url: '/success', method: 'POST' }), |
| 769 |
async onQueryStarted(_, api) { |
| 770 |
api.dispatch(setCount(0)) |
| 771 |
try { |
| 772 |
await api.queryFulfilled |
| 773 |
api.dispatch(setCount(1)) |
| 774 |
} catch { |
| 775 |
api.dispatch(setCount(-1)) |
| 776 |
} |
| 777 |
}, |
| 778 |
}), |
| 779 |
}), |
| 780 |
}) |
| 781 |
|
| 782 |
const storeRef = setupApiStore(api, { testReducer }) |
| 783 |
|
| 784 |
test('query lifecycle events fire properly', async () => { |
| 785 |
// We intentionally fail the first request so we can test all lifecycles |
| 786 |
server.use( |
| 787 |
http.get( |
| 788 |
'https://example.com/success', |
| 789 |
() => HttpResponse.json({ value: 'failed' }, { status: 500 }), |
| 790 |
{ once: true }, |
| 791 |
), |
| 792 |
) |
| 793 |
|
| 794 |
expect(storeRef.store.getState().testReducer.count).toBe(null) |
| 795 |
const failAttempt = storeRef.store.dispatch(api.endpoints.query.initiate()) |
| 796 |
expect(storeRef.store.getState().testReducer.count).toBe(0) |
| 797 |
await failAttempt |
| 798 |
await delay(10) |
| 799 |
expect(storeRef.store.getState().testReducer.count).toBe(-1) |
| 800 |
|
| 801 |
const successAttempt = storeRef.store.dispatch( |
| 802 |
api.endpoints.query.initiate(), |
| 803 |
) |
| 804 |
expect(storeRef.store.getState().testReducer.count).toBe(0) |
| 805 |
await successAttempt |
| 806 |
await delay(10) |
| 807 |
expect(storeRef.store.getState().testReducer.count).toBe(1) |
| 808 |
}) |
| 809 |
|
| 810 |
test('mutation lifecycle events fire properly', async () => { |
| 811 |
// We intentionally fail the first request so we can test all lifecycles |
| 812 |
server.use( |
| 813 |
http.post( |
| 814 |
'https://example.com/success', |
| 815 |
() => HttpResponse.json({ value: 'failed' }, { status: 500 }), |
| 816 |
{ once: true }, |
| 817 |
), |
| 818 |
) |
| 819 |
|
| 820 |
expect(storeRef.store.getState().testReducer.count).toBe(null) |
| 821 |
const failAttempt = storeRef.store.dispatch( |
| 822 |
api.endpoints.mutation.initiate(), |
| 823 |
) |
| 824 |
expect(storeRef.store.getState().testReducer.count).toBe(0) |
| 825 |
await failAttempt |
| 826 |
expect(storeRef.store.getState().testReducer.count).toBe(-1) |
| 827 |
|
| 828 |
const successAttempt = storeRef.store.dispatch( |
| 829 |
api.endpoints.mutation.initiate(), |
| 830 |
) |
| 831 |
expect(storeRef.store.getState().testReducer.count).toBe(0) |
| 832 |
await successAttempt |
| 833 |
expect(storeRef.store.getState().testReducer.count).toBe(1) |
| 834 |
}) |
| 835 |
}) |
| 836 |
|
| 837 |
test('providesTags and invalidatesTags can use baseQueryMeta', async () => { |
| 838 |
let _meta: FetchBaseQueryMeta | undefined |
| 839 |
|
| 840 |
type SuccessResponse = { value: 'success' } |
| 841 |
|
| 842 |
const api = createApi({ |
| 843 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }), |
| 844 |
tagTypes: ['success'], |
| 845 |
endpoints: (build) => ({ |
| 846 |
query: build.query<SuccessResponse, void>({ |
| 847 |
query: () => '/success', |
| 848 |
providesTags: (_result, _error, _arg, meta) => { |
| 849 |
_meta = meta |
| 850 |
return ['success'] |
| 851 |
}, |
| 852 |
}), |
| 853 |
mutation: build.mutation<SuccessResponse, void>({ |
| 854 |
query: () => ({ url: '/success', method: 'POST' }), |
| 855 |
invalidatesTags: (_result, _error, _arg, meta) => { |
| 856 |
_meta = meta |
| 857 |
return ['success'] |
| 858 |
}, |
| 859 |
}), |
| 860 |
}), |
| 861 |
}) |
| 862 |
|
| 863 |
const storeRef = setupApiStore(api, undefined, { |
| 864 |
withoutTestLifecycles: true, |
| 865 |
}) |
| 866 |
|
| 867 |
await storeRef.store.dispatch(api.endpoints.query.initiate()) |
| 868 |
expect('request' in _meta! && 'response' in _meta!).toBe(true) |
| 869 |
|
| 870 |
_meta = undefined |
| 871 |
|
| 872 |
await storeRef.store.dispatch(api.endpoints.mutation.initiate()) |
| 873 |
|
| 874 |
expect('request' in _meta! && 'response' in _meta!).toBe(true) |
| 875 |
}) |
| 876 |
|
| 877 |
describe('structuralSharing flag behaviors', () => { |
| 878 |
type SuccessResponse = { value: 'success' } |
| 879 |
|
| 880 |
const api = createApi({ |
| 881 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }), |
| 882 |
tagTypes: ['success'], |
| 883 |
endpoints: (build) => ({ |
| 884 |
enabled: build.query<SuccessResponse, void>({ |
| 885 |
query: () => '/success', |
| 886 |
}), |
| 887 |
disabled: build.query<SuccessResponse, void>({ |
| 888 |
query: () => ({ url: '/success' }), |
| 889 |
structuralSharing: false, |
| 890 |
}), |
| 891 |
}), |
| 892 |
}) |
| 893 |
|
| 894 |
const storeRef = setupApiStore(api) |
| 895 |
|
| 896 |
it('enables structural sharing for query endpoints by default', async () => { |
| 897 |
await storeRef.store.dispatch(api.endpoints.enabled.initiate()) |
| 898 |
const firstRef = api.endpoints.enabled.select()(storeRef.store.getState()) |
| 899 |
|
| 900 |
await storeRef.store.dispatch( |
| 901 |
api.endpoints.enabled.initiate(undefined, { forceRefetch: true }), |
| 902 |
) |
| 903 |
|
| 904 |
const secondRef = api.endpoints.enabled.select()(storeRef.store.getState()) |
| 905 |
|
| 906 |
expect(firstRef.requestId).not.toEqual(secondRef.requestId) |
| 907 |
expect(firstRef.data === secondRef.data).toBeTruthy() |
| 908 |
}) |
| 909 |
|
| 910 |
it('allows a query endpoint to opt-out of structural sharing', async () => { |
| 911 |
await storeRef.store.dispatch(api.endpoints.disabled.initiate()) |
| 912 |
const firstRef = api.endpoints.disabled.select()(storeRef.store.getState()) |
| 913 |
|
| 914 |
await storeRef.store.dispatch( |
| 915 |
api.endpoints.disabled.initiate(undefined, { forceRefetch: true }), |
| 916 |
) |
| 917 |
|
| 918 |
const secondRef = api.endpoints.disabled.select()(storeRef.store.getState()) |
| 919 |
|
| 920 |
expect(firstRef.requestId).not.toEqual(secondRef.requestId) |
| 921 |
expect(firstRef.data === secondRef.data).toBeFalsy() |
| 922 |
}) |
| 923 |
}) |
| 924 |
|
| 925 |
describe('custom serializeQueryArgs per endpoint', () => { |
| 926 |
const customArgsSerializer: SerializeQueryArgs<number> = ({ |
| 927 |
endpointName, |
| 928 |
queryArgs, |
| 929 |
}) => `${endpointName}-${queryArgs}` |
| 930 |
|
| 931 |
type SuccessResponse = { value: 'success' } |
| 932 |
|
| 933 |
const serializer1 = vi.fn(customArgsSerializer) |
| 934 |
|
| 935 |
interface MyApiClient { |
| 936 |
fetchPost: (id: string) => Promise<SuccessResponse> |
| 937 |
} |
| 938 |
|
| 939 |
const dummyClient: MyApiClient = { |
| 940 |
async fetchPost() { |
| 941 |
return { value: 'success' } |
| 942 |
}, |
| 943 |
} |
| 944 |
|
| 945 |
const api = createApi({ |
| 946 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }), |
| 947 |
serializeQueryArgs: ({ endpointName, queryArgs }) => |
| 948 |
`base-${endpointName}-${queryArgs}`, |
| 949 |
endpoints: (build) => ({ |
| 950 |
queryWithNoSerializer: build.query<SuccessResponse, number>({ |
| 951 |
query: (arg) => `${arg}`, |
| 952 |
}), |
| 953 |
queryWithCustomSerializer: build.query<SuccessResponse, number>({ |
| 954 |
query: (arg) => `${arg}`, |
| 955 |
serializeQueryArgs: serializer1, |
| 956 |
}), |
| 957 |
queryWithCustomObjectSerializer: build.query< |
| 958 |
SuccessResponse, |
| 959 |
{ id: number; client: MyApiClient } |
| 960 |
>({ |
| 961 |
query: (arg) => `${arg.id}`, |
| 962 |
serializeQueryArgs: ({ |
| 963 |
endpointDefinition, |
| 964 |
endpointName, |
| 965 |
queryArgs, |
| 966 |
}) => { |
| 967 |
const { id } = queryArgs |
| 968 |
return { id } |
| 969 |
}, |
| 970 |
}), |
| 971 |
queryWithCustomNumberSerializer: build.query< |
| 972 |
SuccessResponse, |
| 973 |
{ id: number; client: MyApiClient } |
| 974 |
>({ |
| 975 |
query: (arg) => `${arg.id}`, |
| 976 |
serializeQueryArgs: ({ |
| 977 |
endpointDefinition, |
| 978 |
endpointName, |
| 979 |
queryArgs, |
| 980 |
}) => { |
| 981 |
const { id } = queryArgs |
| 982 |
return id |
| 983 |
}, |
| 984 |
}), |
| 985 |
listItems: build.query<string[], number>({ |
| 986 |
query: (pageNumber) => `/listItems?page=${pageNumber}`, |
| 987 |
serializeQueryArgs: ({ endpointName }) => { |
| 988 |
return endpointName |
| 989 |
}, |
| 990 |
merge: (currentCache, newItems) => { |
| 991 |
currentCache.push(...newItems) |
| 992 |
}, |
| 993 |
forceRefetch({ currentArg, previousArg }) { |
| 994 |
return currentArg !== previousArg |
| 995 |
}, |
| 996 |
}), |
| 997 |
listItems2: build.query<{ items: string[]; meta?: any }, number>({ |
| 998 |
query: (pageNumber) => `/listItems2?page=${pageNumber}`, |
| 999 |
serializeQueryArgs: ({ endpointName }) => { |
| 1000 |
return endpointName |
| 1001 |
}, |
| 1002 |
transformResponse(items: string[]) { |
| 1003 |
return { items } |
| 1004 |
}, |
| 1005 |
merge: (currentCache, newData, meta) => { |
| 1006 |
currentCache.items.push(...newData.items) |
| 1007 |
currentCache.meta = meta |
| 1008 |
}, |
| 1009 |
forceRefetch({ currentArg, previousArg }) { |
| 1010 |
return currentArg !== previousArg |
| 1011 |
}, |
| 1012 |
}), |
| 1013 |
}), |
| 1014 |
}) |
| 1015 |
|
| 1016 |
const storeRef = setupApiStore(api) |
| 1017 |
|
| 1018 |
it('Works via createApi', async () => { |
| 1019 |
await storeRef.store.dispatch( |
| 1020 |
api.endpoints.queryWithNoSerializer.initiate(99), |
| 1021 |
) |
| 1022 |
|
| 1023 |
expect(serializer1).not.toHaveBeenCalled() |
| 1024 |
|
| 1025 |
await storeRef.store.dispatch( |
| 1026 |
api.endpoints.queryWithCustomSerializer.initiate(42), |
| 1027 |
) |
| 1028 |
|
| 1029 |
expect(serializer1).toHaveBeenCalled() |
| 1030 |
|
| 1031 |
expect( |
| 1032 |
storeRef.store.getState().api.queries['base-queryWithNoSerializer-99'], |
| 1033 |
).toBeTruthy() |
| 1034 |
|
| 1035 |
expect( |
| 1036 |
storeRef.store.getState().api.queries['queryWithCustomSerializer-42'], |
| 1037 |
).toBeTruthy() |
| 1038 |
}) |
| 1039 |
|
| 1040 |
const serializer2 = vi.fn(customArgsSerializer) |
| 1041 |
|
| 1042 |
const injectedApi = api.injectEndpoints({ |
| 1043 |
endpoints: (build) => ({ |
| 1044 |
injectedQueryWithCustomSerializer: build.query<SuccessResponse, number>({ |
| 1045 |
query: (arg) => `${arg}`, |
| 1046 |
serializeQueryArgs: serializer2, |
| 1047 |
}), |
| 1048 |
}), |
| 1049 |
}) |
| 1050 |
|
| 1051 |
it('Works via injectEndpoints', async () => { |
| 1052 |
expect(serializer2).not.toHaveBeenCalled() |
| 1053 |
|
| 1054 |
await storeRef.store.dispatch( |
| 1055 |
injectedApi.endpoints.injectedQueryWithCustomSerializer.initiate(5), |
| 1056 |
) |
| 1057 |
|
| 1058 |
expect(serializer2).toHaveBeenCalled() |
| 1059 |
expect( |
| 1060 |
storeRef.store.getState().api.queries[ |
| 1061 |
'injectedQueryWithCustomSerializer-5' |
| 1062 |
], |
| 1063 |
).toBeTruthy() |
| 1064 |
}) |
| 1065 |
|
| 1066 |
test('Serializes a returned object for query args', async () => { |
| 1067 |
await storeRef.store.dispatch( |
| 1068 |
api.endpoints.queryWithCustomObjectSerializer.initiate({ |
| 1069 |
id: 42, |
| 1070 |
client: dummyClient, |
| 1071 |
}), |
| 1072 |
) |
| 1073 |
|
| 1074 |
expect( |
| 1075 |
storeRef.store.getState().api.queries[ |
| 1076 |
'queryWithCustomObjectSerializer({"id":42})' |
| 1077 |
], |
| 1078 |
).toBeTruthy() |
| 1079 |
}) |
| 1080 |
|
| 1081 |
test('Serializes a returned primitive for query args', async () => { |
| 1082 |
await storeRef.store.dispatch( |
| 1083 |
api.endpoints.queryWithCustomNumberSerializer.initiate({ |
| 1084 |
id: 42, |
| 1085 |
client: dummyClient, |
| 1086 |
}), |
| 1087 |
) |
| 1088 |
|
| 1089 |
expect( |
| 1090 |
storeRef.store.getState().api.queries[ |
| 1091 |
'queryWithCustomNumberSerializer(42)' |
| 1092 |
], |
| 1093 |
).toBeTruthy() |
| 1094 |
}) |
| 1095 |
|
| 1096 |
test('serializeQueryArgs + merge allows refetching as args change with same cache key', async () => { |
| 1097 |
const allItems = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i'] |
| 1098 |
const PAGE_SIZE = 3 |
| 1099 |
|
| 1100 |
server.use( |
| 1101 |
http.get('https://example.com/listItems', ({ request }) => { |
| 1102 |
const url = new URL(request.url) |
| 1103 |
const pageString = url.searchParams.get('page') |
| 1104 |
const pageNum = parseInt(pageString || '0') |
| 1105 |
|
| 1106 |
const results = paginate(allItems, PAGE_SIZE, pageNum) |
| 1107 |
return HttpResponse.json(results) |
| 1108 |
}), |
| 1109 |
) |
| 1110 |
|
| 1111 |
// Page number shouldn't matter here, because the cache key ignores that. |
| 1112 |
// We just need to select the only cache entry. |
| 1113 |
const selectListItems = api.endpoints.listItems.select(0) |
| 1114 |
|
| 1115 |
await storeRef.store.dispatch(api.endpoints.listItems.initiate(1)) |
| 1116 |
|
| 1117 |
const initialEntry = selectListItems(storeRef.store.getState()) |
| 1118 |
expect(initialEntry.data).toEqual(['a', 'b', 'c']) |
| 1119 |
|
| 1120 |
await storeRef.store.dispatch(api.endpoints.listItems.initiate(2)) |
| 1121 |
const updatedEntry = selectListItems(storeRef.store.getState()) |
| 1122 |
expect(updatedEntry.data).toEqual(['a', 'b', 'c', 'd', 'e', 'f']) |
| 1123 |
}) |
| 1124 |
|
| 1125 |
test('merge receives a meta object as an argument', async () => { |
| 1126 |
const allItems = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i'] |
| 1127 |
const PAGE_SIZE = 3 |
| 1128 |
|
| 1129 |
server.use( |
| 1130 |
http.get('https://example.com/listItems2', ({ request }) => { |
| 1131 |
const url = new URL(request.url) |
| 1132 |
const pageString = url.searchParams.get('page') |
| 1133 |
const pageNum = parseInt(pageString || '0') |
| 1134 |
|
| 1135 |
const results = paginate(allItems, PAGE_SIZE, pageNum) |
| 1136 |
return HttpResponse.json(results) |
| 1137 |
}), |
| 1138 |
) |
| 1139 |
|
| 1140 |
const selectListItems = api.endpoints.listItems2.select(0) |
| 1141 |
|
| 1142 |
await storeRef.store.dispatch(api.endpoints.listItems2.initiate(1)) |
| 1143 |
await storeRef.store.dispatch(api.endpoints.listItems2.initiate(2)) |
| 1144 |
const cacheEntry = selectListItems(storeRef.store.getState()) |
| 1145 |
|
| 1146 |
// Should have passed along the third arg from `merge` containing these fields |
| 1147 |
expect(cacheEntry.data?.meta).toEqual({ |
| 1148 |
requestId: expect.any(String), |
| 1149 |
fulfilledTimeStamp: expect.any(Number), |
| 1150 |
arg: 2, |
| 1151 |
baseQueryMeta: expect.any(Object), |
| 1152 |
}) |
| 1153 |
}) |
| 1154 |
}) |
| 1155 |
|
| 1156 |
describe('timeout behavior', () => { |
| 1157 |
test('triggers TIMEOUT_ERROR', async () => { |
| 1158 |
const api = createApi({ |
| 1159 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com', timeout: 5 }), |
| 1160 |
endpoints: (build) => ({ |
| 1161 |
query: build.query<unknown, void>({ |
| 1162 |
query: () => '/success', |
| 1163 |
}), |
| 1164 |
}), |
| 1165 |
}) |
| 1166 |
|
| 1167 |
const storeRef = setupApiStore(api, undefined, { |
| 1168 |
withoutTestLifecycles: true, |
| 1169 |
}) |
| 1170 |
|
| 1171 |
server.use( |
| 1172 |
http.get( |
| 1173 |
'https://example.com/success', |
| 1174 |
async () => { |
| 1175 |
await delay(10) |
| 1176 |
return HttpResponse.json({ value: 'failed' }, { status: 500 }) |
| 1177 |
}, |
| 1178 |
{ once: true }, |
| 1179 |
), |
| 1180 |
) |
| 1181 |
|
| 1182 |
const result = await storeRef.store.dispatch(api.endpoints.query.initiate()) |
| 1183 |
|
| 1184 |
expect(result?.error).toEqual({ |
| 1185 |
status: 'TIMEOUT_ERROR', |
| 1186 |
error: expect.stringMatching(/^AbortError:/), |
| 1187 |
}) |
| 1188 |
}) |
| 1189 |
}) |