|
1 | 1 | import { describe, expect, test, vi, expectTypeOf } from "vitest"; |
2 | 2 | import { defineComponent, h } from "vue"; |
3 | | -import type { AxiosResponse } from "axios"; |
| 3 | +import type { AxiosRequestConfig, AxiosResponse } from "axios"; |
4 | 4 | import axios from "axios"; |
5 | 5 |
|
6 | 6 | import AxiosUseVue, { useRequest, _request } from "../src"; |
@@ -186,4 +186,62 @@ describe("useRequest", () => { |
186 | 186 | expect(response).toStrictEqual(mockItem); |
187 | 187 | expectTypeOf(response).toMatchTypeOf<MockDataUserItem | undefined>(); |
188 | 188 | }); |
| 189 | + |
| 190 | + test("custom response (custom request and getResponseItem)", async () => { |
| 191 | + const TARGET_ID = "1"; |
| 192 | + const mockItem = MOCK_DATA_USER_LIST.find((i) => i.id === TARGET_ID); |
| 193 | + |
| 194 | + type _MyRes<T> = { status: number; result?: T; message?: string }; |
| 195 | + |
| 196 | + const _getResponseItem = (r: _MyRes<unknown>) => r.result; |
| 197 | + const _instance = axios.create({ |
| 198 | + baseURL: BASE_URL, |
| 199 | + }); |
| 200 | + _instance.interceptors.response.use( |
| 201 | + (d) => |
| 202 | + ({ |
| 203 | + status: (d.data?.code as number) || d.status, |
| 204 | + result: d.data, |
| 205 | + message: d.data?.msg || d.statusText, |
| 206 | + } as any), |
| 207 | + ); |
| 208 | + const myrequest = <T>(config: AxiosRequestConfig) => |
| 209 | + _request<{ status: number; result?: T; message?: string }, any, "result">( |
| 210 | + config, |
| 211 | + ); |
| 212 | + |
| 213 | + const [createRequest] = useRequest( |
| 214 | + (id: string) => |
| 215 | + myrequest<MockDataUserItem>({ |
| 216 | + method: "get", |
| 217 | + url: `/user/${id}`, |
| 218 | + }), |
| 219 | + { |
| 220 | + instance: _instance, |
| 221 | + getResponseItem: _getResponseItem, |
| 222 | + onCompleted: (d, r) => { |
| 223 | + expect(d).toStrictEqual(mockItem); |
| 224 | + expectTypeOf(d).toMatchTypeOf<MockDataUserItem | undefined>(); |
| 225 | + expect(r).toStrictEqual({ |
| 226 | + status: 200, |
| 227 | + result: mockItem, |
| 228 | + message: "OK", |
| 229 | + }); |
| 230 | + expectTypeOf(r).toMatchTypeOf<_MyRes<MockDataUserItem> | undefined>(); |
| 231 | + }, |
| 232 | + }, |
| 233 | + ); |
| 234 | + |
| 235 | + const [data, response] = await createRequest(TARGET_ID).ready(); |
| 236 | + expect(data).toStrictEqual(mockItem); |
| 237 | + expectTypeOf(data).toMatchTypeOf<MockDataUserItem | undefined>(); |
| 238 | + expect(response).toStrictEqual({ |
| 239 | + status: 200, |
| 240 | + result: mockItem, |
| 241 | + message: "OK", |
| 242 | + }); |
| 243 | + expectTypeOf(response).toMatchTypeOf< |
| 244 | + _MyRes<MockDataUserItem> | undefined |
| 245 | + >(); |
| 246 | + }); |
189 | 247 | }); |
0 commit comments