|
| 1 | +import { describe, expect, test, vi } from "vitest"; |
| 2 | +import retry from "."; |
| 3 | + |
| 4 | +describe("retry 유틸 함수 테스트", () => { |
| 5 | + test("정상적으로 실행되는 함수는 한번만 실행한다.", async () => { |
| 6 | + const fn = vi.fn().mockResolvedValue("success!"); |
| 7 | + |
| 8 | + const result = await retry(fn, 3); |
| 9 | + |
| 10 | + expect(result).toBe("success!"); |
| 11 | + expect(fn).toHaveBeenCalledTimes(1); |
| 12 | + }); |
| 13 | + |
| 14 | + test("함수를 실행하며 오류가 발생하면 재시도한다.", async () => { |
| 15 | + const fn = vi |
| 16 | + .fn() |
| 17 | + .mockRejectedValueOnce(new Error("fail 1")) |
| 18 | + .mockRejectedValueOnce(new Error("fail 2")) |
| 19 | + .mockResolvedValue("success!"); |
| 20 | + |
| 21 | + const result = await retry(fn, 3); |
| 22 | + |
| 23 | + expect(result).toBe("success!"); |
| 24 | + expect(fn).toHaveBeenCalledTimes(3); |
| 25 | + }); |
| 26 | + |
| 27 | + test("재시도 한도를 초과하면 마지막 에러를 던진다.", async () => { |
| 28 | + const error = new Error("always fail"); |
| 29 | + const fn = vi.fn().mockRejectedValue(error); |
| 30 | + |
| 31 | + await expect(retry(fn, 2)).rejects.toThrow("always fail"); |
| 32 | + expect(fn).toHaveBeenCalledTimes(2); |
| 33 | + }); |
| 34 | + |
| 35 | + test("기본 재시도 횟수는 3번이다.", async () => { |
| 36 | + const fn = vi.fn().mockRejectedValue(new Error("fail")); |
| 37 | + |
| 38 | + await expect(retry(fn)).rejects.toThrow("fail"); |
| 39 | + expect(fn).toHaveBeenCalledTimes(3); |
| 40 | + }); |
| 41 | + |
| 42 | + test("타입 안전성: 반환 타입이 올바르게 추론된다.", async () => { |
| 43 | + const stringFn = vi.fn().mockResolvedValue("hello"); |
| 44 | + const numberFn = vi.fn().mockResolvedValue(42); |
| 45 | + const objectFn = vi.fn().mockResolvedValue({ id: 1 }); |
| 46 | + |
| 47 | + const stringResult = await retry(stringFn); |
| 48 | + const numberResult = await retry(numberFn); |
| 49 | + const objectResult = await retry(objectFn); |
| 50 | + |
| 51 | + expect(typeof stringResult).toBe("string"); |
| 52 | + expect(typeof numberResult).toBe("number"); |
| 53 | + expect(typeof objectResult).toBe("object"); |
| 54 | + |
| 55 | + expect(stringResult).toBe("hello"); |
| 56 | + expect(numberResult).toBe(42); |
| 57 | + expect(objectResult).toEqual({ id: 1 }); |
| 58 | + }); |
| 59 | + |
| 60 | + test("0번 재시도 시 한 번만 실행한다.", async () => { |
| 61 | + const fn = vi.fn().mockRejectedValue(new Error("fail")); |
| 62 | + |
| 63 | + await expect(retry(fn, 0)).rejects.toThrow("fail"); |
| 64 | + expect(fn).toHaveBeenCalledTimes(1); |
| 65 | + }); |
| 66 | +}); |
0 commit comments