|
1 |
| -import { configureStore } from '@reduxjs/toolkit' |
| 1 | +import { configureStore, isAllOf } from '@reduxjs/toolkit' |
2 | 2 | import { createApi } from '@reduxjs/toolkit/query/react'
|
3 | 3 | import { renderHook, waitFor } from '@testing-library/react'
|
4 |
| -import { withProvider } from '../../tests/utils/helpers' |
| 4 | +import { actionsReducer, withProvider } from '../../tests/utils/helpers' |
5 | 5 | import type { BaseQueryApi } from '../baseQueryTypes'
|
6 | 6 |
|
7 | 7 | test('handles a non-async baseQuery without error', async () => {
|
@@ -200,3 +200,52 @@ describe('re-triggering behavior on arg change', () => {
|
200 | 200 | }
|
201 | 201 | })
|
202 | 202 | })
|
| 203 | + |
| 204 | +describe('prefetch', () => { |
| 205 | + const baseQuery = () => ({ data: null }) |
| 206 | + const api = createApi({ |
| 207 | + baseQuery, |
| 208 | + endpoints: (build) => ({ |
| 209 | + getUser: build.query<any, any>({ |
| 210 | + query: (obj) => obj, |
| 211 | + }), |
| 212 | + }), |
| 213 | + }) |
| 214 | + |
| 215 | + const store = configureStore({ |
| 216 | + reducer: { [api.reducerPath]: api.reducer, ...actionsReducer }, |
| 217 | + middleware: (gDM) => gDM().concat(api.middleware), |
| 218 | + }) |
| 219 | + it('should attach isPrefetch if prefetching', async () => { |
| 220 | + store.dispatch(api.util.prefetch('getUser', 1, {})) |
| 221 | + |
| 222 | + await Promise.all(store.dispatch(api.util.getRunningQueriesThunk())) |
| 223 | + |
| 224 | + const isPrefetch = ( |
| 225 | + action: any, |
| 226 | + ): action is { meta: { arg: { isPrefetch: true } } } => |
| 227 | + action?.meta?.arg?.isPrefetch |
| 228 | + |
| 229 | + expect(store.getState().actions).toMatchSequence( |
| 230 | + api.internalActions.middlewareRegistered.match, |
| 231 | + isAllOf(api.endpoints.getUser.matchPending, isPrefetch), |
| 232 | + isAllOf(api.endpoints.getUser.matchFulfilled, isPrefetch), |
| 233 | + ) |
| 234 | + |
| 235 | + // compare against a regular initiate call |
| 236 | + await store.dispatch( |
| 237 | + api.endpoints.getUser.initiate(1, { forceRefetch: true }), |
| 238 | + ) |
| 239 | + |
| 240 | + const isNotPrefetch = (action: any): action is unknown => |
| 241 | + !isPrefetch(action) |
| 242 | + |
| 243 | + expect(store.getState().actions).toMatchSequence( |
| 244 | + api.internalActions.middlewareRegistered.match, |
| 245 | + isAllOf(api.endpoints.getUser.matchPending, isPrefetch), |
| 246 | + isAllOf(api.endpoints.getUser.matchFulfilled, isPrefetch), |
| 247 | + isAllOf(api.endpoints.getUser.matchPending, isNotPrefetch), |
| 248 | + isAllOf(api.endpoints.getUser.matchFulfilled, isNotPrefetch), |
| 249 | + ) |
| 250 | + }) |
| 251 | +}) |
0 commit comments