Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/src/query/tests/fetchBaseQuery.test.tsx

raw
1 import { createSlice } from '@reduxjs/toolkit'
2 import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
3 import { headersToObject } from 'headers-polyfill'
4 import { HttpResponse, delay, http } from 'msw'
5 // @ts-ignore
6 import nodeFetch from 'node-fetch'
7 import queryString from 'query-string'
8 import { vi } from 'vitest'
9 import { setupApiStore } from '../../tests/utils/helpers'
10 import type { BaseQueryApi } from '../baseQueryTypes'
11 import { server } from './mocks/server'
12
13 const defaultHeaders: Record<string, string> = {
14 fake: 'header',
15 delete: 'true',
16 delete2: '1',
17 }
18
19 const baseUrl = 'https://example.com'
20
21 // @ts-ignore
22 const fetchFn = vi.fn<Promise<any>, any[]>(nodeFetch)
23
24 const baseQuery = fetchBaseQuery({
25 baseUrl,
26 fetchFn: fetchFn as any,
27 prepareHeaders: (headers, { getState }) => {
28 const { token } = (getState() as RootState).auth
29
30 // If we have a token set in state, let's assume that we should be passing it.
31 if (token) {
32 headers.set('authorization', `Bearer ${token}`)
33 }
34 // A user could customize their behavior here, so we'll just test that custom scenarios would work.
35 const potentiallyConflictingKeys = Object.keys(defaultHeaders)
36 potentiallyConflictingKeys.forEach((key) => {
37 // Check for presence of a default key, if the incoming endpoint headers don't specify it as '', then set it
38 const existingValue = headers.get(key)
39 if (!existingValue && existingValue !== '') {
40 headers.set(key, String(defaultHeaders[key]))
41 // If an endpoint sets a header with a value of '', just delete the header.
42 } else if (headers.get(key) === '') {
43 headers.delete(key)
44 }
45 })
46
47 return headers
48 },
49 })
50
51 const api = createApi({
52 baseQuery,
53 endpoints(build) {
54 return {
55 query: build.query({ query: () => ({ url: '/echo', headers: {} }) }),
56 mutation: build.mutation({
57 query: () => ({ url: '/echo', method: 'POST', credentials: 'omit' }),
58 }),
59 }
60 },
61 })
62
63 const authSlice = createSlice({
64 name: 'auth',
65 initialState: {
66 token: '',
67 },
68 reducers: {
69 setToken(state, action) {
70 state.token = action.payload
71 },
72 },
73 })
74
75 const storeRef = setupApiStore(api, { auth: authSlice.reducer })
76 type RootState = ReturnType<typeof storeRef.store.getState>
77
78 let commonBaseQueryApi: BaseQueryApi = {} as any
79 beforeEach(() => {
80 let abortController = new AbortController()
81 commonBaseQueryApi = {
82 signal: abortController.signal,
83 abort: (reason) =>
84 // @ts-ignore
85 abortController.abort(reason),
86 dispatch: storeRef.store.dispatch,
87 getState: storeRef.store.getState,
88 extra: undefined,
89 type: 'query',
90 endpoint: 'doesntmatterhere',
91 }
92 })
93
94 describe('fetchBaseQuery', () => {
95 describe('basic functionality', () => {
96 it('should return an object for a simple GET request when it is json data', async () => {
97 const req = baseQuery('/success', commonBaseQueryApi, {})
98 expect(req).toBeInstanceOf(Promise)
99 const res = await req
100 expect(res).toBeInstanceOf(Object)
101 expect(res.data).toEqual({ value: 'success' })
102 })
103
104 it('should return undefined for a simple GET request when the response is empty', async () => {
105 const req = baseQuery('/empty', commonBaseQueryApi, {})
106 expect(req).toBeInstanceOf(Promise)
107 const res = await req
108 expect(res).toBeInstanceOf(Object)
109 expect(res.meta?.request).toBeInstanceOf(Request)
110 expect(res.meta?.response).toBeInstanceOf(Object)
111
112 expect(res.data).toBeNull()
113 })
114
115 it('should return an error and status for error responses', async () => {
116 const req = baseQuery('/error', commonBaseQueryApi, {})
117 expect(req).toBeInstanceOf(Promise)
118 const res = await req
119 expect(res).toBeInstanceOf(Object)
120 expect(res.meta?.request).toBeInstanceOf(Request)
121 expect(res.meta?.response).toBeInstanceOf(Object)
122 expect(res.error).toEqual({
123 status: 500,
124 data: { value: 'error' },
125 })
126 })
127
128 it('should handle a connection loss semi-gracefully', async () => {
129 fetchFn.mockRejectedValueOnce(new TypeError('Failed to fetch'))
130
131 const req = baseQuery('/success', commonBaseQueryApi, {})
132 expect(req).toBeInstanceOf(Promise)
133 const res = await req
134 expect(res).toBeInstanceOf(Object)
135 expect(res.meta?.request).toBeInstanceOf(Request)
136 expect(res.meta?.response).toBe(undefined)
137 expect(res.error).toEqual({
138 status: 'FETCH_ERROR',
139 error: 'TypeError: Failed to fetch',
140 })
141 })
142 })
143
144 describe('non-JSON-body', () => {
145 it('success: should return data ("text" responseHandler)', async () => {
146 server.use(
147 http.get(
148 'https://example.com/success',
149 () => HttpResponse.text(`this is not json!`),
150 { once: true },
151 ),
152 )
153
154 const req = baseQuery(
155 { url: '/success', responseHandler: 'text' },
156 commonBaseQueryApi,
157 {},
158 )
159 expect(req).toBeInstanceOf(Promise)
160 const res = await req
161 expect(res).toBeInstanceOf(Object)
162 expect(res.meta?.request).toBeInstanceOf(Request)
163 expect(res.meta?.response).toBeInstanceOf(Object)
164 expect(res.data).toEqual(`this is not json!`)
165 })
166
167 it('success: should fail gracefully (default="json" responseHandler)', async () => {
168 server.use(
169 http.get(
170 'https://example.com/success',
171 () => HttpResponse.text(`this is not json!`),
172 { once: true },
173 ),
174 )
175
176 const req = baseQuery('/success', commonBaseQueryApi, {})
177 expect(req).toBeInstanceOf(Promise)
178 const res = await req
179 expect(res).toBeInstanceOf(Object)
180 expect(res.meta?.request).toBeInstanceOf(Request)
181 expect(res.meta?.response).toBeInstanceOf(Object)
182 expect(res.error).toEqual({
183 status: 'PARSING_ERROR',
184 error: expect.stringMatching(/SyntaxError: Unexpected token/),
185 originalStatus: 200,
186 data: `this is not json!`,
187 })
188 })
189
190 it('success: parse text without error ("content-type" responseHandler)', async () => {
191 server.use(
192 http.get(
193 'https://example.com/success',
194 () => HttpResponse.text(`this is not json!`),
195 { once: true },
196 ),
197 )
198
199 const req = baseQuery(
200 {
201 url: '/success',
202 responseHandler: 'content-type',
203 },
204 commonBaseQueryApi,
205 {},
206 )
207 expect(req).toBeInstanceOf(Promise)
208 const res = await req
209 expect(res).toBeInstanceOf(Object)
210 expect(res.meta?.response?.headers.get('content-type')).toEqual(
211 'text/plain',
212 )
213 expect(res.meta?.request).toBeInstanceOf(Request)
214 expect(res.meta?.response).toBeInstanceOf(Object)
215 expect(res.data).toEqual(`this is not json!`)
216 })
217
218 it('success: parse json without error ("content-type" responseHandler)', async () => {
219 server.use(
220 http.get(
221 'https://example.com/success',
222 () => HttpResponse.json(`this will become json!`),
223 { once: true },
224 ),
225 )
226
227 const req = baseQuery(
228 {
229 url: '/success',
230 responseHandler: 'content-type',
231 },
232 commonBaseQueryApi,
233 {},
234 )
235 expect(req).toBeInstanceOf(Promise)
236 const res = await req
237 expect(res).toBeInstanceOf(Object)
238 expect(res.meta?.response?.headers.get('content-type')).toEqual(
239 'application/json',
240 )
241 expect(res.meta?.request).toBeInstanceOf(Request)
242 expect(res.meta?.response).toBeInstanceOf(Object)
243 expect(res.data).toEqual(`this will become json!`)
244 })
245
246 it('server error: should fail normally with a 500 status ("text" responseHandler)', async () => {
247 server.use(
248 http.get('https://example.com/error', () =>
249 HttpResponse.text(`this is not json!`, { status: 500 }),
250 ),
251 )
252
253 const req = baseQuery(
254 { url: '/error', responseHandler: 'text' },
255 commonBaseQueryApi,
256 {},
257 )
258 expect(req).toBeInstanceOf(Promise)
259 const res = await req
260 expect(res).toBeInstanceOf(Object)
261 expect(res.meta?.request).toBeInstanceOf(Request)
262 expect(res.meta?.response).toBeInstanceOf(Object)
263 expect(res.error).toEqual({
264 status: 500,
265 data: `this is not json!`,
266 })
267 })
268
269 it('server error: should fail normally with a 500 status as text ("content-type" responseHandler)', async () => {
270 const serverResponse = 'Internal Server Error'
271 server.use(
272 http.get('https://example.com/error', () =>
273 HttpResponse.text(serverResponse, { status: 500 }),
274 ),
275 )
276
277 const req = baseQuery(
278 { url: '/error', responseHandler: 'content-type' },
279 commonBaseQueryApi,
280 {},
281 )
282 expect(req).toBeInstanceOf(Promise)
283 const res = await req
284 expect(res).toBeInstanceOf(Object)
285 expect(res.meta?.request).toBeInstanceOf(Request)
286 expect(res.meta?.response).toBeInstanceOf(Object)
287 expect(res.meta?.response?.headers.get('content-type')).toEqual(
288 'text/plain',
289 )
290 expect(res.error).toEqual({
291 status: 500,
292 data: serverResponse,
293 })
294 })
295
296 it('server error: should fail normally with a 500 status as json ("content-type" responseHandler)', async () => {
297 const serverResponse = {
298 errors: { field1: "Password cannot be 'password'" },
299 }
300 server.use(
301 http.get('https://example.com/error', () =>
302 HttpResponse.json(serverResponse, { status: 500 }),
303 ),
304 )
305
306 const req = baseQuery(
307 { url: '/error', responseHandler: 'content-type' },
308 commonBaseQueryApi,
309 {},
310 )
311 expect(req).toBeInstanceOf(Promise)
312 const res = await req
313 expect(res).toBeInstanceOf(Object)
314 expect(res.meta?.request).toBeInstanceOf(Request)
315 expect(res.meta?.response).toBeInstanceOf(Object)
316 expect(res.meta?.response?.headers.get('content-type')).toEqual(
317 'application/json',
318 )
319 expect(res.error).toEqual({
320 status: 500,
321 data: serverResponse,
322 })
323 })
324
325 it('server error: should fail gracefully (default="json" responseHandler)', async () => {
326 server.use(
327 http.get('https://example.com/error', () =>
328 HttpResponse.text(`this is not json!`, { status: 500 }),
329 ),
330 )
331
332 const req = baseQuery('/error', commonBaseQueryApi, {})
333 expect(req).toBeInstanceOf(Promise)
334 const res = await req
335 expect(res).toBeInstanceOf(Object)
336 expect(res.meta?.request).toBeInstanceOf(Request)
337 expect(res.meta?.response).toBeInstanceOf(Object)
338 expect(res.error).toEqual({
339 status: 'PARSING_ERROR',
340 error: expect.stringMatching(/SyntaxError: Unexpected token/),
341 originalStatus: 500,
342 data: `this is not json!`,
343 })
344 })
345 })
346
347 describe('arg.body', () => {
348 test('an object provided to body will be serialized when content-type is json', async () => {
349 const data = {
350 test: 'value',
351 }
352
353 let request: any
354 ;({ data: request } = await baseQuery(
355 { url: '/echo', body: data, method: 'POST' },
356 { ...commonBaseQueryApi, type: 'mutation' },
357 {},
358 ))
359
360 expect(request.headers['content-type']).toBe('application/json')
361 expect(request.body).toEqual(data)
362 })
363
364 test('an array provided to body will be serialized when content-type is json', async () => {
365 const data = ['test', 'value']
366
367 let request: any
368 ;({ data: request } = await baseQuery(
369 { url: '/echo', body: data, method: 'POST' },
370 commonBaseQueryApi,
371 {},
372 ))
373
374 expect(request.headers['content-type']).toBe('application/json')
375 expect(request.body).toEqual(data)
376 })
377
378 test('an object provided to body will not be serialized when content-type is not json', async () => {
379 const data = {
380 test: 'value',
381 }
382
383 let request: any
384 ;({ data: request } = await baseQuery(
385 {
386 url: '/echo',
387 body: data,
388 method: 'POST',
389 headers: { 'content-type': 'text/html' },
390 },
391 commonBaseQueryApi,
392 {},
393 ))
394
395 expect(request.headers['content-type']).toBe('text/html')
396 expect(request.body).toEqual('[object Object]')
397 })
398
399 test('an array provided to body will not be serialized when content-type is not json', async () => {
400 const data = ['test', 'value']
401
402 let request: any
403 ;({ data: request } = await baseQuery(
404 {
405 url: '/echo',
406 body: data,
407 method: 'POST',
408 headers: { 'content-type': 'text/html' },
409 },
410 commonBaseQueryApi,
411 {},
412 ))
413
414 expect(request.headers['content-type']).toBe('text/html')
415 expect(request.body).toEqual(data.join(','))
416 })
417
418 it('supports a custom jsonContentType', async () => {
419 const baseQuery = fetchBaseQuery({
420 baseUrl,
421 fetchFn: fetchFn as any,
422 jsonContentType: 'application/vnd.api+json',
423 })
424
425 let request: any
426 ;({ data: request } = await baseQuery(
427 {
428 url: '/echo',
429 body: {},
430 method: 'POST',
431 },
432 commonBaseQueryApi,
433 {},
434 ))
435
436 expect(request.headers['content-type']).toBe('application/vnd.api+json')
437 })
438
439 it('supports a custom jsonReplacer', async () => {
440 const body = {
441 items: new Set(['A', 'B', 'C']),
442 }
443
444 let request: any
445 ;({ data: request } = await baseQuery(
446 {
447 url: '/echo',
448 body,
449 method: 'POST',
450 },
451 commonBaseQueryApi,
452 {},
453 ))
454
455 expect(request.headers['content-type']).toBe('application/json')
456 expect(request.body).toEqual({ items: {} }) // Set is not properly marshalled by default
457
458 // Use jsonReplacer
459 const baseQueryWithReplacer = fetchBaseQuery({
460 baseUrl,
461 fetchFn: fetchFn as any,
462 jsonReplacer: (key, value) =>
463 value instanceof Set ? [...value] : value,
464 })
465
466 ;({ data: request } = await baseQueryWithReplacer(
467 {
468 url: '/echo',
469 body,
470 method: 'POST',
471 },
472 commonBaseQueryApi,
473 {},
474 ))
475
476 expect(request.headers['content-type']).toBe('application/json')
477 expect(request.body).toEqual({ items: ['A', 'B', 'C'] }) // Set is marshalled correctly by jsonReplacer
478 })
479 })
480
481 describe('arg.params', () => {
482 it('should not serialize missing params', async () => {
483 let request: any
484 ;({ data: request } = await baseQuery(
485 { url: '/echo' },
486 commonBaseQueryApi,
487 {},
488 ))
489
490 expect(request.url).toEqual(`${baseUrl}/echo`)
491 })
492
493 it('should serialize numeric and boolean params', async () => {
494 const params = { a: 1, b: true }
495
496 let request: any
497 ;({ data: request } = await baseQuery(
498 { url: '/echo', params },
499 commonBaseQueryApi,
500 {},
501 ))
502
503 expect(request.url).toEqual(`${baseUrl}/echo?a=1&b=true`)
504 })
505
506 it('should merge params into existing url querystring', async () => {
507 const params = { a: 1, b: true }
508
509 let request: any
510 ;({ data: request } = await baseQuery(
511 { url: '/echo?banana=pudding', params },
512 commonBaseQueryApi,
513 {},
514 ))
515
516 expect(request.url).toEqual(`${baseUrl}/echo?banana=pudding&a=1&b=true`)
517 })
518
519 it('should accept a URLSearchParams instance', async () => {
520 const params = new URLSearchParams({ apple: 'fruit' })
521
522 let request: any
523 ;({ data: request } = await baseQuery(
524 { url: '/echo', params },
525 commonBaseQueryApi,
526 {},
527 ))
528
529 expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`)
530 })
531
532 it('should strip undefined values from the end params', async () => {
533 const params = { apple: 'fruit', banana: undefined, randy: null }
534
535 let request: any
536 ;({ data: request } = await baseQuery(
537 { url: '/echo', params },
538 commonBaseQueryApi,
539 {},
540 ))
541
542 expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit&randy=null`)
543 })
544
545 it('should support a paramsSerializer', async () => {
546 const baseQuery = fetchBaseQuery({
547 baseUrl,
548 fetchFn: fetchFn as any,
549 paramsSerializer: (params: Record<string, unknown>) =>
550 queryString.stringify(params, { arrayFormat: 'bracket' }),
551 })
552
553 const api = createApi({
554 baseQuery,
555 endpoints(build) {
556 return {
557 query: build.query({
558 query: () => ({ url: '/echo', headers: {} }),
559 }),
560 mutation: build.mutation({
561 query: () => ({
562 url: '/echo',
563 method: 'POST',
564 credentials: 'omit',
565 }),
566 }),
567 }
568 },
569 })
570
571 const params = {
572 someArray: ['a', 'b', 'c'],
573 }
574
575 let request: any
576 ;({ data: request } = await baseQuery(
577 { url: '/echo', params },
578 commonBaseQueryApi,
579 {},
580 ))
581
582 expect(request.url).toEqual(
583 `${baseUrl}/echo?someArray[]=a&someArray[]=b&someArray[]=c`,
584 )
585 })
586
587 it('should supports a custom isJsonContentType function', async () => {
588 const testBody = {
589 i_should_be_stringified: true,
590 }
591 const baseQuery = fetchBaseQuery({
592 baseUrl,
593 fetchFn: fetchFn as any,
594 isJsonContentType: (headers) =>
595 [
596 'application/vnd.api+json',
597 'application/json',
598 'application/vnd.hal+json',
599 ].includes(headers.get('content-type') ?? ''),
600 })
601
602 let request: any
603 ;({ data: request } = await baseQuery(
604 {
605 url: '/echo',
606 method: 'POST',
607 body: testBody,
608 headers: { 'content-type': 'application/vnd.hal+json' },
609 },
610 commonBaseQueryApi,
611 {},
612 ))
613
614 expect(request.body).toMatchObject(testBody)
615 })
616 })
617
618 describe('validateStatus', () => {
619 test('validateStatus can return an error even on normal 200 responses', async () => {
620 // This is a scenario where an API may always return a 200, but indicates there is an error when success = false
621 const res = await baseQuery(
622 {
623 url: '/nonstandard-error',
624 validateStatus: (response, body) =>
625 response.status === 200 && body.success === false ? false : true,
626 },
627 commonBaseQueryApi,
628 {},
629 )
630
631 expect(res.error).toEqual({
632 status: 200,
633 data: {
634 success: false,
635 message: 'This returns a 200 but is really an error',
636 },
637 })
638 })
639 })
640
641 describe('arg.headers and prepareHeaders', () => {
642 test('uses the default headers set in prepareHeaders', async () => {
643 let request: any
644 ;({ data: request } = await baseQuery(
645 { url: '/echo' },
646 commonBaseQueryApi,
647 {},
648 ))
649
650 expect(request.headers['fake']).toBe(defaultHeaders['fake'])
651 expect(request.headers['delete']).toBe(defaultHeaders['delete'])
652 expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
653 })
654
655 test('adds endpoint-level headers to the defaults', async () => {
656 let request: any
657 ;({ data: request } = await baseQuery(
658 { url: '/echo', headers: { authorization: 'Bearer banana' } },
659 commonBaseQueryApi,
660 {},
661 ))
662
663 expect(request.headers['authorization']).toBe('Bearer banana')
664 expect(request.headers['fake']).toBe(defaultHeaders['fake'])
665 expect(request.headers['delete']).toBe(defaultHeaders['delete'])
666 expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
667 })
668
669 test('it does not set application/json when content-type is set', async () => {
670 let request: any
671 ;({ data: request } = await baseQuery(
672 {
673 url: '/echo',
674 headers: {
675 authorization: 'Bearer banana',
676 'content-type': 'custom-content-type',
677 },
678 },
679 commonBaseQueryApi,
680 {},
681 ))
682
683 expect(request.headers['authorization']).toBe('Bearer banana')
684 expect(request.headers['content-type']).toBe('custom-content-type')
685 expect(request.headers['fake']).toBe(defaultHeaders['fake'])
686 expect(request.headers['delete']).toBe(defaultHeaders['delete'])
687 expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
688 })
689
690 test('respects the headers from an endpoint over the base headers', async () => {
691 const fake = 'fake endpoint value'
692
693 let request: any
694 ;({ data: request } = await baseQuery(
695 { url: '/echo', headers: { fake, delete: '', delete2: '' } },
696 commonBaseQueryApi,
697 {},
698 ))
699
700 expect(request.headers['fake']).toBe(fake)
701 expect(request.headers['delete']).toBeUndefined()
702 expect(request.headers['delete2']).toBeUndefined()
703 })
704
705 test('prepareHeaders can return undefined', async () => {
706 let request: any
707
708 const token = 'accessToken'
709
710 const _baseQuery = fetchBaseQuery({
711 baseUrl,
712 prepareHeaders: (headers) => {
713 headers.set('authorization', `Bearer ${token}`)
714 },
715 })
716
717 const doRequest = async () =>
718 _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
719
720 ;({ data: request } = await doRequest())
721
722 expect(request.headers['authorization']).toBe(`Bearer ${token}`)
723 })
724
725 test('prepareHeaders is able to be an async function', async () => {
726 let request: any
727
728 const token = 'accessToken'
729 const getAccessTokenAsync = async () => token
730
731 const _baseQuery = fetchBaseQuery({
732 baseUrl,
733 prepareHeaders: async (headers) => {
734 headers.set('authorization', `Bearer ${await getAccessTokenAsync()}`)
735 return headers
736 },
737 })
738
739 const doRequest = async () =>
740 _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
741
742 ;({ data: request } = await doRequest())
743
744 expect(request.headers['authorization']).toBe(`Bearer ${token}`)
745 })
746
747 test('prepareHeaders is able to be an async function returning undefined', async () => {
748 let request: any
749
750 const token = 'accessToken'
751 const getAccessTokenAsync = async () => token
752
753 const _baseQuery = fetchBaseQuery({
754 baseUrl,
755 prepareHeaders: async (headers) => {
756 headers.set('authorization', `Bearer ${await getAccessTokenAsync()}`)
757 },
758 })
759
760 const doRequest = async () =>
761 _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
762
763 ;({ data: request } = await doRequest())
764
765 expect(request.headers['authorization']).toBe(`Bearer ${token}`)
766 })
767
768 test('prepareHeaders is able to select from a state', async () => {
769 let request: any
770
771 const doRequest = async () => {
772 const abortController = new AbortController()
773 return baseQuery(
774 { url: '/echo' },
775 {
776 signal: abortController.signal,
777 abort: (reason) =>
778 // @ts-ignore
779 abortController.abort(reason),
780 dispatch: storeRef.store.dispatch,
781 getState: storeRef.store.getState,
782 extra: undefined,
783 type: 'query',
784 endpoint: '',
785 },
786 {},
787 )
788 }
789
790 ;({ data: request } = await doRequest())
791
792 expect(request.headers['authorization']).toBeUndefined()
793
794 // Set a token and the follow up request should have the header injected by prepareHeaders
795 const token = 'fakeToken!'
796 storeRef.store.dispatch(authSlice.actions.setToken(token))
797 ;({ data: request } = await doRequest())
798
799 expect(request.headers['authorization']).toBe(`Bearer ${token}`)
800 })
801
802 test('prepareHeaders provides extra api information for getState, extra, endpoint, type and forced', async () => {
803 let _getState, _arg: any, _extra, _endpoint, _type, _forced
804
805 const baseQuery = fetchBaseQuery({
806 baseUrl,
807 fetchFn: fetchFn as any,
808 prepareHeaders: (
809 headers,
810 { getState, arg, extra, endpoint, type, forced },
811 ) => {
812 _getState = getState
813 _arg = arg
814 _endpoint = endpoint
815 _type = type
816 _forced = forced
817 _extra = extra
818
819 return headers
820 },
821 })
822
823 const fakeAuth0Client = {
824 getTokenSilently: async () => 'fakeToken',
825 }
826
827 const doRequest = async () => {
828 const abortController = new AbortController()
829 return baseQuery(
830 { url: '/echo' },
831 {
832 signal: abortController.signal,
833 abort: (reason) =>
834 // @ts-ignore
835 abortController.abort(reason),
836 dispatch: storeRef.store.dispatch,
837 getState: storeRef.store.getState,
838 extra: fakeAuth0Client,
839 type: 'query',
840 forced: true,
841 endpoint: 'someEndpointName',
842 },
843 {},
844 )
845 }
846
847 await doRequest()
848
849 expect(_getState).toBeDefined()
850 expect(_arg!.url).toBe('/echo')
851 expect(_endpoint).toBe('someEndpointName')
852 expect(_type).toBe('query')
853 expect(_forced).toBe(true)
854 expect(_extra).toBe(fakeAuth0Client)
855 })
856
857 test('can be instantiated with a `ExtraOptions` generic and `extraOptions` will be available in `prepareHeaders', async () => {
858 const prepare = vitest.fn()
859 const baseQuery = fetchBaseQuery({
860 prepareHeaders(headers, api) {
861 expectTypeOf(api.extraOptions).toEqualTypeOf<unknown>()
862 prepare.apply(undefined, arguments as unknown as any[])
863 },
864 })
865 baseQuery('https://example.com', commonBaseQueryApi, {
866 foo: 'baz',
867 bar: 5,
868 })
869 expect(prepare).toHaveBeenCalledWith(
870 expect.anything(),
871 expect.objectContaining({ extraOptions: { foo: 'baz', bar: 5 } }),
872 )
873
874 // ensure types
875 createApi({
876 baseQuery,
877 endpoints(build) {
878 return {
879 testQuery: build.query({
880 query: () => ({ url: '/echo', headers: {} }),
881 extraOptions: {
882 foo: 'asd',
883 bar: 1,
884 },
885 }),
886 testMutation: build.mutation({
887 query: () => ({
888 url: '/echo',
889 method: 'POST',
890 credentials: 'omit',
891 }),
892 extraOptions: {
893 foo: 'qwe',
894 bar: 15,
895 },
896 }),
897 }
898 },
899 })
900 })
901 })
902
903 test('can pass `headers` into `fetchBaseQuery`', async () => {
904 let request: any
905
906 const token = 'accessToken'
907
908 const _baseQuery = fetchBaseQuery({
909 baseUrl,
910 headers: { authorization: `Bearer ${token}` },
911 })
912
913 const doRequest = async () =>
914 _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
915
916 ;({ data: request } = await doRequest())
917
918 expect(request.headers['authorization']).toBe(`Bearer ${token}`)
919 })
920
921 test('lets a header be undefined', async () => {
922 let request: any
923 ;({ data: request } = await baseQuery(
924 { url: '/echo', headers: undefined },
925 commonBaseQueryApi,
926 {},
927 ))
928
929 expect(request.headers['fake']).toBe(defaultHeaders['fake'])
930 expect(request.headers['delete']).toBe(defaultHeaders['delete'])
931 expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
932 })
933
934 test('allows for possibly undefined header key/values', async () => {
935 const banana = '1' as '1' | undefined
936 let request: any
937 ;({ data: request } = await baseQuery(
938 { url: '/echo', headers: { banana } },
939 commonBaseQueryApi,
940 {},
941 ))
942
943 expect(request.headers['banana']).toBe('1')
944 expect(request.headers['fake']).toBe(defaultHeaders['fake'])
945 expect(request.headers['delete']).toBe(defaultHeaders['delete'])
946 expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
947 })
948
949 test('strips undefined values from the headers', async () => {
950 const banana = undefined as '1' | undefined
951 let request: any
952 ;({ data: request } = await baseQuery(
953 { url: '/echo', headers: { banana } },
954 commonBaseQueryApi,
955 {},
956 ))
957
958 expect(request.headers['banana']).toBeUndefined()
959 expect(request.headers['fake']).toBe(defaultHeaders['fake'])
960 expect(request.headers['delete']).toBe(defaultHeaders['delete'])
961 expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
962 })
963
964 describe('Accepts global arguments', () => {
965 test('Global responseHandler', async () => {
966 server.use(
967 http.get(
968 'https://example.com/success',
969 () => HttpResponse.text(`this is not json!`),
970 { once: true },
971 ),
972 )
973
974 const globalizedBaseQuery = fetchBaseQuery({
975 baseUrl,
976 fetchFn: fetchFn as any,
977 responseHandler: 'text',
978 })
979
980 const req = globalizedBaseQuery(
981 { url: '/success' },
982 commonBaseQueryApi,
983 {},
984 )
985 expect(req).toBeInstanceOf(Promise)
986 const res = await req
987 expect(res).toBeInstanceOf(Object)
988 expect(res.meta?.request).toBeInstanceOf(Request)
989 expect(res.meta?.response).toBeInstanceOf(Object)
990 expect(res.error).toBeUndefined()
991 expect(res.data).toEqual(`this is not json!`)
992 })
993
994 test('Global validateStatus', async () => {
995 const globalizedBaseQuery = fetchBaseQuery({
996 baseUrl,
997 fetchFn: fetchFn as any,
998 validateStatus: (response, body) =>
999 response.status === 200 && body.success === false ? false : true,
1000 })
1001
1002 // This is a scenario where an API may always return a 200, but indicates there is an error when success = false
1003 const res = await globalizedBaseQuery(
1004 {
1005 url: '/nonstandard-error',
1006 },
1007 commonBaseQueryApi,
1008 {},
1009 )
1010
1011 expect(res.error).toEqual({
1012 status: 200,
1013 data: {
1014 success: false,
1015 message: 'This returns a 200 but is really an error',
1016 },
1017 })
1018 })
1019
1020 test('Global timeout', async () => {
1021 server.use(
1022 http.get(
1023 'https://example.com/empty1',
1024 async ({ request, cookies, params, requestId }) => {
1025 await delay(300)
1026
1027 return HttpResponse.json({
1028 ...request,
1029 cookies,
1030 params,
1031 requestId,
1032 url: new URL(request.url),
1033 headers: headersToObject(request.headers),
1034 })
1035 },
1036 { once: true },
1037 ),
1038 )
1039
1040 const globalizedBaseQuery = fetchBaseQuery({
1041 baseUrl,
1042 fetchFn: fetchFn as any,
1043 timeout: 200,
1044 })
1045
1046 const result = await globalizedBaseQuery(
1047 { url: '/empty1' },
1048 commonBaseQueryApi,
1049 {},
1050 )
1051
1052 expect(result?.error).toEqual({
1053 status: 'TIMEOUT_ERROR',
1054 error: expect.stringMatching(/^AbortError:/),
1055 })
1056 })
1057 })
1058 })
1059
1060 describe('fetchFn', () => {
1061 test('accepts a custom fetchFn', async () => {
1062 const baseUrl = 'https://example.com'
1063 const params = new URLSearchParams({ apple: 'fruit' })
1064
1065 const baseQuery = fetchBaseQuery({
1066 baseUrl,
1067 fetchFn: nodeFetch as any,
1068 })
1069 let request: any
1070 ;({ data: request } = await baseQuery(
1071 { url: '/echo', params },
1072 commonBaseQueryApi,
1073 {},
1074 ))
1075
1076 expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`)
1077 })
1078
1079 test('respects mocking window.fetch after a fetch base query is created', async () => {
1080 const baseUrl = 'https://example.com'
1081 const baseQuery = fetchBaseQuery({ baseUrl })
1082
1083 const fakeResponse = {
1084 ok: true,
1085 status: 200,
1086 text: async () => `{ "url": "mock-return-url" }`,
1087 clone: () => fakeResponse,
1088 }
1089
1090 const spiedFetch = vi.spyOn(window, 'fetch')
1091 spiedFetch.mockResolvedValueOnce(fakeResponse as any)
1092
1093 const { data } = await baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
1094 expect(data).toEqual({ url: 'mock-return-url' })
1095
1096 spiedFetch.mockClear()
1097 })
1098 })
1099
1100 describe('FormData', () => {
1101 test('sets the right headers when sending FormData', async () => {
1102 const body = new FormData()
1103
1104 body.append('username', 'test')
1105
1106 body.append(
1107 'file',
1108 new Blob([JSON.stringify({ hello: 'there' }, null, 2)], {
1109 type: 'application/json',
1110 }),
1111 )
1112
1113 const res = await baseQuery(
1114 { url: '/echo', method: 'POST', body },
1115 commonBaseQueryApi,
1116 {},
1117 )
1118
1119 const request: any = res.data
1120
1121 expect(request.headers['content-type']).not.toContain('application/json')
1122 })
1123 })
1124
1125 describe('still throws on completely unexpected errors', () => {
1126 test('', async () => {
1127 const error = new Error('some unexpected error')
1128 const req = baseQuery(
1129 {
1130 url: '/success',
1131 validateStatus() {
1132 throw error
1133 },
1134 },
1135 commonBaseQueryApi,
1136 {},
1137 )
1138 expect(req).toBeInstanceOf(Promise)
1139 await expect(req).rejects.toBe(error)
1140 })
1141 })
1142
1143 describe('timeout', () => {
1144 test('throws a timeout error when a request takes longer than specified timeout duration', async () => {
1145 server.use(
1146 http.get(
1147 'https://example.com/empty2',
1148 async ({ request, cookies, params, requestId }) => {
1149 await delay(300)
1150
1151 return HttpResponse.json({
1152 ...request,
1153 url: new URL(request.url),
1154 cookies,
1155 params,
1156 requestId,
1157 headers: headersToObject(request.headers),
1158 })
1159 },
1160 { once: true },
1161 ),
1162 )
1163
1164 const result = await baseQuery(
1165 { url: '/empty2', timeout: 200 },
1166 commonBaseQueryApi,
1167 {},
1168 )
1169
1170 expect(result?.error).toEqual({
1171 status: 'TIMEOUT_ERROR',
1172 error: expect.stringMatching(/^AbortError:/),
1173 })
1174 })
1175 })