From 6acdb5bdc075198fdd0539b0fda00b3a35dd1ec2 Mon Sep 17 00:00:00 2001 From: K-shir0 Date: Fri, 7 Jul 2023 01:06:47 +0900 Subject: [PATCH] =?UTF-8?q?add:=20userGroups=20=E3=81=AE=20hooks=20?= =?UTF-8?q?=E3=83=86=E3=82=B9=E3=83=88=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- __test__/hooks/userGroups.test.ts | 64 +++++++++++++++++++++++++++++++ hooks/userGroups.tsx | 1 + 2 files changed, 65 insertions(+) create mode 100644 __test__/hooks/userGroups.test.ts diff --git a/__test__/hooks/userGroups.test.ts b/__test__/hooks/userGroups.test.ts new file mode 100644 index 0000000..cc9d2ee --- /dev/null +++ b/__test__/hooks/userGroups.test.ts @@ -0,0 +1,64 @@ +import { renderHook } from "@testing-library/react"; +import useSWR from "swr"; +import { Mock, vi } from "vitest"; + +import useUserGroups from "@/hooks/userGroups"; +import { testUserGroup, UserGroup } from "@/types/UserGroup"; +import { Result } from "@/types/_api"; + +vi.mock("swr"); + +beforeEach(() => { + // toHaveBeenCalledTimes がテストごとにリセットされるようにする + vi.clearAllMocks(); +}); + +describe("useUserGroups", () => { + it("ユーザーグループ一覧を取得できる", () => { + // setup + const mockResult: Result = { + code: 200, + data: [testUserGroup], + }; + + (useSWR as Mock).mockReturnValue({ + data: mockResult, + isLoading: false, + }); + + // when + const { result } = renderHook(() => useUserGroups()); + + // then + expect(useSWR).toBeCalledWith("usergroups", expect.any(Function)); + expect(result.current.userGroups).toEqual(mockResult.data); + expect(result.current.isLoading).toEqual(false); + + // verify + expect(useSWR).toBeCalledTimes(1); + }); + + it("取得したユーザーグループ一覧が空の時 userGroups が Null になる", () => { + // setup + const mockResult: Result = { + code: 200, + data: null, + }; + + (useSWR as Mock).mockReturnValue({ + data: mockResult, + isLoading: false, + }); + + // when + const { result } = renderHook(() => useUserGroups()); + + // then + expect(useSWR).toBeCalledWith("usergroups", expect.any(Function)); + expect(result.current.userGroups).toBeNull(); + expect(result.current.isLoading).toEqual(false); + + // verify + expect(useSWR).toBeCalledTimes(1); + }); +}); diff --git a/hooks/userGroups.tsx b/hooks/userGroups.tsx index bb9b70a..d1e858f 100644 --- a/hooks/userGroups.tsx +++ b/hooks/userGroups.tsx @@ -6,6 +6,7 @@ import { UserGroup } from "@/types/UserGroup"; const useUserGroups = () => { const { client } = useApi(); + /* c8 ignore next */ const fetcher = (url: string) => client.get(url); const { data, isLoading } = useSWR("usergroups", fetcher);