1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| import { act, renderHook } from "@testing-library/react"; import { useAsync } from "utils/use-async";
const defaultState: ReturnType<typeof useAsync> = { stat: "idle", error: null, data: null, isIdle: true, isLoading: false, isError: false, isSuccess: false, run: expect.any(Function), setData: expect.any(Function), setError: expect.any(Function), retry: expect.any(Function), };
const loadingState: ReturnType<typeof useAsync> = { ...defaultState, stat: "loading", isLoading: true, isIdle: false, }; const successState: ReturnType<typeof useAsync> = { ...defaultState, stat: "success", isSuccess: true, isIdle: false, };
test("useAsync可以异步处理", async () => { let resolve: any, reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
const { result } = renderHook(() => useAsync()); expect(result.current).toEqual(defaultState);
let p: Promise<any>; act(() => { p = result.current.run(promise); }); expect(result.current).toEqual(loadingState);
const resolvedValue = { mockValue: "resolved" }; act(async () => { resolve(resolvedValue); await p; }); expect(result.current).toEqual({ ...successState, data: resolvedValue, }); });
|