| 1 |
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' |
| 2 |
import { useState } from 'react' |
| 3 |
|
| 4 |
const mockSuccessResponse = { value: 'success' } |
| 5 |
|
| 6 |
const api = createApi({ |
| 7 |
baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }), |
| 8 |
endpoints: (build) => ({ |
| 9 |
update: build.mutation<typeof mockSuccessResponse, any>({ |
| 10 |
query: () => ({ url: 'success' }), |
| 11 |
}), |
| 12 |
failedUpdate: build.mutation<typeof mockSuccessResponse, any>({ |
| 13 |
query: () => ({ url: 'error' }), |
| 14 |
}), |
| 15 |
}), |
| 16 |
}) |
| 17 |
|
| 18 |
describe('type tests', () => { |
| 19 |
test('a mutation is unwrappable and has the correct types', () => { |
| 20 |
function User() { |
| 21 |
const [manualError, setManualError] = useState<any>() |
| 22 |
|
| 23 |
const [update, { isLoading, data, error }] = |
| 24 |
api.endpoints.update.useMutation() |
| 25 |
|
| 26 |
return ( |
| 27 |
<div> |
| 28 |
<div data-testid="isLoading">{String(isLoading)}</div> |
| 29 |
<div data-testid="data">{JSON.stringify(data)}</div> |
| 30 |
<div data-testid="error">{JSON.stringify(error)}</div> |
| 31 |
<div data-testid="manuallySetError"> |
| 32 |
{JSON.stringify(manualError)} |
| 33 |
</div> |
| 34 |
<button |
| 35 |
onClick={() => { |
| 36 |
update({ name: 'hello' }) |
| 37 |
.unwrap() |
| 38 |
.then((result) => { |
| 39 |
expectTypeOf(result).toEqualTypeOf(mockSuccessResponse) |
| 40 |
|
| 41 |
setManualError(undefined) |
| 42 |
}) |
| 43 |
.catch(setManualError) |
| 44 |
}} |
| 45 |
> |
| 46 |
Update User |
| 47 |
</button> |
| 48 |
</div> |
| 49 |
) |
| 50 |
} |
| 51 |
}) |
| 52 |
}) |