Skip to content
This repository has been archived by the owner on Jul 24, 2023. It is now read-only.

Commit

Permalink
add: notice の hooks テストを追加
Browse files Browse the repository at this point in the history
  • Loading branch information
K-shir0 committed Jul 6, 2023
1 parent b88c9ca commit 06a82f4
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
66 changes: 66 additions & 0 deletions __test__/hooks/notice.test.ts
Original file line number Diff line number Diff line change
@@ -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<Notice[]> = {
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<Notice[]> = {
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);
});
});
1 change: 1 addition & 0 deletions hooks/notice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Notice } from "@/types/Notice";
const useNotice = () => {
const { client } = useApi();

/* c8 ignore next */
const fetcher = (url: string) => client.get<Notice[]>(url);

const { data, mutate, isLoading } = useSWR("notices", fetcher);
Expand Down
7 changes: 7 additions & 0 deletions types/Notice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};

0 comments on commit 06a82f4

Please sign in to comment.