| 1 |
import type { SerializedError } from '@reduxjs/toolkit' |
| 2 |
import { createSlice } from '@reduxjs/toolkit' |
| 3 |
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' |
| 4 |
|
| 5 |
interface ResultType { |
| 6 |
result: 'complex' |
| 7 |
} |
| 8 |
|
| 9 |
interface ArgType { |
| 10 |
foo: 'bar' |
| 11 |
count: 3 |
| 12 |
} |
| 13 |
|
| 14 |
const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' }) |
| 15 |
const api = createApi({ |
| 16 |
baseQuery, |
| 17 |
endpoints(build) { |
| 18 |
return { |
| 19 |
querySuccess: build.query<ResultType, ArgType>({ |
| 20 |
query: () => '/success', |
| 21 |
}), |
| 22 |
querySuccess2: build.query({ query: () => '/success' }), |
| 23 |
queryFail: build.query({ query: () => '/error' }), |
| 24 |
mutationSuccess: build.mutation({ |
| 25 |
query: () => ({ url: '/success', method: 'POST' }), |
| 26 |
}), |
| 27 |
mutationSuccess2: build.mutation({ |
| 28 |
query: () => ({ url: '/success', method: 'POST' }), |
| 29 |
}), |
| 30 |
mutationFail: build.mutation({ |
| 31 |
query: () => ({ url: '/error', method: 'POST' }), |
| 32 |
}), |
| 33 |
} |
| 34 |
}, |
| 35 |
}) |
| 36 |
|
| 37 |
describe('type tests', () => { |
| 38 |
test('inferred types', () => { |
| 39 |
createSlice({ |
| 40 |
name: 'auth', |
| 41 |
initialState: {}, |
| 42 |
reducers: {}, |
| 43 |
extraReducers: (builder) => { |
| 44 |
builder |
| 45 |
.addMatcher( |
| 46 |
api.endpoints.querySuccess.matchPending, |
| 47 |
(state, action) => { |
| 48 |
expectTypeOf(action.payload).toBeUndefined() |
| 49 |
|
| 50 |
expectTypeOf( |
| 51 |
action.meta.arg.originalArgs, |
| 52 |
).toEqualTypeOf<ArgType>() |
| 53 |
}, |
| 54 |
) |
| 55 |
.addMatcher( |
| 56 |
api.endpoints.querySuccess.matchFulfilled, |
| 57 |
(state, action) => { |
| 58 |
expectTypeOf(action.payload).toEqualTypeOf<ResultType>() |
| 59 |
|
| 60 |
expectTypeOf(action.meta.fulfilledTimeStamp).toBeNumber() |
| 61 |
|
| 62 |
expectTypeOf( |
| 63 |
action.meta.arg.originalArgs, |
| 64 |
).toEqualTypeOf<ArgType>() |
| 65 |
}, |
| 66 |
) |
| 67 |
.addMatcher( |
| 68 |
api.endpoints.querySuccess.matchRejected, |
| 69 |
(state, action) => { |
| 70 |
expectTypeOf(action.error).toEqualTypeOf<SerializedError>() |
| 71 |
|
| 72 |
expectTypeOf( |
| 73 |
action.meta.arg.originalArgs, |
| 74 |
).toEqualTypeOf<ArgType>() |
| 75 |
}, |
| 76 |
) |
| 77 |
}, |
| 78 |
}) |
| 79 |
}) |
| 80 |
}) |