File tree Expand file tree Collapse file tree 3 files changed +244
-11
lines changed
packages/toolkit/src/query Expand file tree Collapse file tree 3 files changed +244
-11
lines changed Original file line number Diff line number Diff line change @@ -27,6 +27,13 @@ export interface FetchArgs extends CustomRequestInit {
27
27
validateStatus ?: ( response : Response , body : any ) => boolean
28
28
}
29
29
30
+ /**
31
+ * A mini-wrapper that passes arguments straight through to
32
+ * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.
33
+ * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.
34
+ */
35
+ const defaultFetchFn : typeof fetch = ( ...args ) => fetch ( ...args )
36
+
30
37
const defaultValidateStatus = ( response : Response ) =>
31
38
response . status >= 200 && response . status <= 299
32
39
@@ -118,7 +125,7 @@ export type FetchBaseQueryMeta = { request: Request; response: Response }
118
125
export function fetchBaseQuery ( {
119
126
baseUrl,
120
127
prepareHeaders = ( x ) => x ,
121
- fetchFn = fetch ,
128
+ fetchFn = defaultFetchFn ,
122
129
...baseFetchOptions
123
130
} : FetchBaseQueryArgs = { } ) : BaseQueryFn <
124
131
string | FetchArgs ,
@@ -127,6 +134,11 @@ export function fetchBaseQuery({
127
134
{ } ,
128
135
FetchBaseQueryMeta
129
136
> {
137
+ if ( typeof fetch === 'undefined' && fetchFn === defaultFetchFn ) {
138
+ console . warn (
139
+ 'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.'
140
+ )
141
+ }
130
142
return async ( arg , { signal, getState } ) => {
131
143
let {
132
144
url,
Original file line number Diff line number Diff line change @@ -531,6 +531,34 @@ describe('fetchFn', () => {
531
531
532
532
expect ( request . url ) . toEqual ( `${ baseUrl } /echo?apple=fruit` )
533
533
} )
534
+
535
+ test ( 'respects mocking window.fetch after a fetch base query is created' , async ( ) => {
536
+ const baseUrl = 'http://example.com'
537
+ const baseQuery = fetchBaseQuery ( { baseUrl } )
538
+
539
+ const fakeResponse = {
540
+ ok : true ,
541
+ status : 200 ,
542
+ text : async ( ) => `{ "url": "mock-return-url" }` ,
543
+ clone : ( ) => fakeResponse
544
+ }
545
+
546
+ const spiedFetch = jest . spyOn ( window , 'fetch' ) ;
547
+ spiedFetch . mockResolvedValueOnce ( fakeResponse as any ) ;
548
+
549
+ const { data } = await baseQuery (
550
+ { url : '/echo' } ,
551
+ {
552
+ signal : new AbortController ( ) . signal ,
553
+ dispatch : storeRef . store . dispatch ,
554
+ getState : storeRef . store . getState ,
555
+ } ,
556
+ { }
557
+ )
558
+ expect ( data ) . toEqual ( { url : 'mock-return-url' } )
559
+
560
+ spiedFetch . mockClear ( ) ;
561
+ } )
534
562
} )
535
563
536
564
describe ( 'FormData' , ( ) => {
You can’t perform that action at this time.
0 commit comments