Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Prevent closure over fetch #1267

Merged
merged 4 commits into from
Jul 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion packages/toolkit/src/query/fetchBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ export interface FetchArgs extends CustomRequestInit {
validateStatus?: (response: Response, body: any) => boolean
}

/**
* A mini-wrapper that passes arguments straight through to
* {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.
* Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.
*/
const defaultFetchFn: typeof fetch = (...args) => fetch(...args)

const defaultValidateStatus = (response: Response) =>
response.status >= 200 && response.status <= 299

Expand Down Expand Up @@ -118,7 +125,7 @@ export type FetchBaseQueryMeta = { request: Request; response: Response }
export function fetchBaseQuery({
baseUrl,
prepareHeaders = (x) => x,
fetchFn = fetch,
fetchFn = defaultFetchFn,
...baseFetchOptions
}: FetchBaseQueryArgs = {}): BaseQueryFn<
string | FetchArgs,
Expand All @@ -127,6 +134,11 @@ export function fetchBaseQuery({
{},
FetchBaseQueryMeta
> {
if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {
console.warn(
'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.'
)
}
return async (arg, { signal, getState }) => {
let {
url,
Expand Down
28 changes: 28 additions & 0 deletions packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,34 @@ describe('fetchFn', () => {

expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`)
})

test('respects mocking window.fetch after a fetch base query is created', async () => {
const baseUrl = 'http://example.com'
const baseQuery = fetchBaseQuery({ baseUrl })

const fakeResponse = {
ok: true,
status: 200,
text: async () => `{ "url": "mock-return-url" }`,
clone: () => fakeResponse
}

const spiedFetch = jest.spyOn(window, 'fetch');
spiedFetch.mockResolvedValueOnce(fakeResponse as any);

const { data } = await baseQuery(
{ url: '/echo' },
{
signal: new AbortController().signal,
dispatch: storeRef.store.dispatch,
getState: storeRef.store.getState,
},
{}
)
expect(data).toEqual({url: 'mock-return-url'})

spiedFetch.mockClear();
})
})

describe('FormData', () => {
Expand Down
Loading