Skip to content

Commit 498ff77

Browse files
committed
Also throw error from query hooks if middleware not registered
1 parent 1e983cc commit 498ff77

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

packages/toolkit/src/query/react/buildHooks.ts

+9
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,15 @@ export function buildHooks<Definitions extends EndpointDefinitions>({
716716
})
717717
)
718718

719+
if (process.env.NODE_ENV !== 'production') {
720+
if (typeof returnedValue !== 'boolean') {
721+
throw new Error(
722+
`Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
723+
You must add the middleware for RTK-Query to function correctly!`
724+
)
725+
}
726+
}
727+
719728
currentRenderHasSubscription = !!returnedValue
720729
}
721730

packages/toolkit/src/query/tests/buildHooks.test.tsx

+39-1
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,18 @@ import {
1818
expectExactType,
1919
expectType,
2020
setupApiStore,
21+
withProvider,
2122
useRenderCounter,
2223
waitMs,
2324
} from './helpers'
2425
import { server } from './mocks/server'
2526
import type { AnyAction } from 'redux'
2627
import type { SubscriptionOptions } from '@reduxjs/toolkit/dist/query/core/apiState'
27-
import { createListenerMiddleware, SerializedError } from '@reduxjs/toolkit'
28+
import {
29+
createListenerMiddleware,
30+
SerializedError,
31+
configureStore,
32+
} from '@reduxjs/toolkit'
2833
import { renderHook } from '@testing-library/react'
2934
import { delay } from '../../utils'
3035

@@ -651,6 +656,39 @@ describe('hooks tests', () => {
651656
const res = await resPromise
652657
expect(res.data!.amount).toBeGreaterThan(originalAmount)
653658
})
659+
660+
describe('Hook middleware requirements', () => {
661+
let mock: jest.SpyInstance
662+
663+
beforeEach(() => {
664+
mock = jest.spyOn(console, 'error').mockImplementation(() => {})
665+
})
666+
667+
afterEach(() => {
668+
mock.mockReset()
669+
})
670+
671+
test('Throws error if middleware is not added to the store', async () => {
672+
const store = configureStore({
673+
reducer: {
674+
[api.reducerPath]: api.reducer,
675+
},
676+
})
677+
678+
const doRender = () => {
679+
const { result } = renderHook(
680+
() => api.endpoints.getIncrementedAmount.useQuery(),
681+
{
682+
wrapper: withProvider(store),
683+
}
684+
)
685+
}
686+
687+
expect(doRender).toThrowError(
688+
/Warning: Middleware for RTK-Query API at reducerPath "api" has not been added to the store/
689+
)
690+
})
691+
})
654692
})
655693

656694
describe('useLazyQuery', () => {

0 commit comments

Comments
 (0)