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 2 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 `window.fetch`.
* Avoids storing `window.fetch` in a closure, in order to permit mocking/monkey-patching.
*/
const defaultFetchFn = (...args: Parameters<typeof window.fetch>) =>
window.fetch(...args)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const defaultFetchFn = (...args: Parameters<typeof window.fetch>) =>
window.fetch(...args)
const defaultFetchFn: typeof fetch = (...args) =>
fetch(...args)

Given that we had it without the window reference before, let's just keep it like that.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No problem, changed as per the above, and tweaked the docstring slightly.

The reason I explicitly changed it previously was that I've experienced a setup where Sinon's useFakeTimers will mock window.setTimeout but not setTimeout. But given that I haven't found the exact reason for that, or how version specific or test setup specific the behaviour is, I can't assume that will occur elsewhere.


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 window === 'undefined' && fetchFn === defaultFetchFn) {
console.warn(
'Warning: `window` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.'
)
}
phryneas marked this conversation as resolved.
Show resolved Hide resolved
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