|
| 1 | +import { beforeEach, describe, expect, test, vi } from "vitest"; |
| 2 | +import { createLazyProxy } from "./create-lazy-proxy"; |
| 3 | + |
| 4 | +describe("createLazyProxy", () => { |
| 5 | + describe("Proxy生成時", () => { |
| 6 | + const initializer = vi.fn(); |
| 7 | + |
| 8 | + beforeEach(() => { |
| 9 | + initializer.mockReturnValue({ key: "value" }); |
| 10 | + createLazyProxy(initializer); |
| 11 | + }); |
| 12 | + |
| 13 | + test("初期化関数が呼ばれないこと", () => { |
| 14 | + expect(initializer).not.toHaveBeenCalled(); |
| 15 | + }); |
| 16 | + }); |
| 17 | + |
| 18 | + describe("プロパティに初めてアクセスしたとき", () => { |
| 19 | + const initializer = vi.fn(); |
| 20 | + |
| 21 | + beforeEach(() => { |
| 22 | + initializer.mockReturnValue({ key: "value" }); |
| 23 | + }); |
| 24 | + |
| 25 | + test("初期化関数が呼ばれること", () => { |
| 26 | + const proxy = createLazyProxy(initializer); |
| 27 | + |
| 28 | + proxy.key; |
| 29 | + |
| 30 | + expect(initializer).toHaveBeenCalledTimes(1); |
| 31 | + }); |
| 32 | + }); |
| 33 | + |
| 34 | + describe("プロパティに複数回アクセスしたとき", () => { |
| 35 | + const initializer = vi.fn(); |
| 36 | + |
| 37 | + beforeEach(() => { |
| 38 | + initializer.mockReturnValue({ a: 1, b: 2 }); |
| 39 | + }); |
| 40 | + |
| 41 | + test("初期化関数が1回だけ呼ばれること", () => { |
| 42 | + const proxy = createLazyProxy(initializer); |
| 43 | + |
| 44 | + proxy.a; |
| 45 | + proxy.b; |
| 46 | + proxy.a; |
| 47 | + |
| 48 | + expect(initializer).toHaveBeenCalledTimes(1); |
| 49 | + }); |
| 50 | + }); |
| 51 | + |
| 52 | + describe("プロパティアクセスの委譲", () => { |
| 53 | + const initializer = vi.fn(); |
| 54 | + |
| 55 | + beforeEach(() => { |
| 56 | + initializer.mockReturnValue({ name: "test", count: 42 }); |
| 57 | + }); |
| 58 | + |
| 59 | + test("初期化されたオブジェクトのプロパティ値が返ること", () => { |
| 60 | + const proxy = createLazyProxy<{ name: string; count: number }>( |
| 61 | + initializer, |
| 62 | + ); |
| 63 | + |
| 64 | + expect(proxy.name).toBe("test"); |
| 65 | + expect(proxy.count).toBe(42); |
| 66 | + }); |
| 67 | + }); |
| 68 | +}); |
0 commit comments