diff --git a/__test__/hooks/notice.test.ts b/__test__/hooks/notice.test.ts new file mode 100644 index 0000000..45ef8a2 --- /dev/null +++ b/__test__/hooks/notice.test.ts @@ -0,0 +1,66 @@ +import { renderHook } from "@testing-library/react"; +import useSWR from "swr"; +import { Mock, vi } from "vitest"; + +import useNotice from "@/hooks/notice"; +import { Notice, testNotice } from "@/types/Notice"; +import { Result } from "@/types/_api"; + +vi.mock("swr"); + +beforeEach(() => { + // toHaveBeenCalledTimes がテストごとにリセットされるようにする + vi.clearAllMocks(); +}); + +describe("useNotice", () => { + it("通知一覧が取得できる", () => { + // setup + const mockResult: Result = { + code: 200, + data: [testNotice], + }; + + (useSWR as Mock).mockReturnValue({ + data: mockResult, + mutate: vi.fn(), + isLoading: false, + }); + + // when + const { result } = renderHook(() => useNotice()); + + // then + expect(useSWR).toBeCalledWith("notices", expect.any(Function)); + expect(result.current.notices).toEqual(mockResult.data); + expect(result.current.mutate).toBeDefined(); + + // verify + expect(useSWR).toBeCalledTimes(1); + }); + + it("取得した通知一覧が空の時 notices が空になる", () => { + // setup + const mockResult: Result = { + code: 200, + data: null, + }; + + (useSWR as Mock).mockReturnValue({ + data: mockResult, + mutate: vi.fn(), + isLoading: false, + }); + + // when + const { result } = renderHook(() => useNotice()); + + // then + expect(useSWR).toBeCalledWith("notices", expect.any(Function)); + expect(result.current.notices).toBeNull(); + expect(result.current.mutate).toBeDefined(); + + // verify + expect(useSWR).toBeCalledTimes(1); + }); +}); diff --git a/hooks/notice.ts b/hooks/notice.ts index 66eabff..48b045c 100644 --- a/hooks/notice.ts +++ b/hooks/notice.ts @@ -6,6 +6,7 @@ import { Notice } from "@/types/Notice"; const useNotice = () => { const { client } = useApi(); + /* c8 ignore next */ const fetcher = (url: string) => client.get(url); const { data, mutate, isLoading } = useSWR("notices", fetcher); diff --git a/types/Notice.ts b/types/Notice.ts index e0412dc..33c2c51 100644 --- a/types/Notice.ts +++ b/types/Notice.ts @@ -4,3 +4,10 @@ export type Notice = { body?: string; draft: boolean; }; + +export const testNotice: Notice = { + source_id: "1", + title: "Test Notice", + body: "Test Notice Body", + draft: false, +};