// @vitest-environment jsdom import { render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; import { MemoryRouter } from "react-router-dom"; import { createTechLogFeatureInstalledInput } from "../../../src/features/tech-log/adapters/create-tech-log-feature-input.ts"; import type { PublicTopic, PublicTopicDetail, } from "../../../src/features/tech-log/application/ports/public-content-queries.ts"; import { HomeTopicTabs } from "../../../src/features/tech-log/presentation/public/components/home-topic-tabs.tsx"; import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx"; import { createTestApplication } from "../../helpers/create-test-application.ts"; import { renderWithQueryProviders } from "../../helpers/query-providers.tsx"; import { MOCK_STUDIO_INSTALL_CONTEXT } from "../../helpers/studio-install-context.ts"; /** * 홈이 주제 하나만 펴 두던 동안, 나머지로 가는 길은 비교 목록 밑의 작은 글씨 한 줄뿐이었다 — * 다 읽고 나서야 만나는 자리라 대개 지나쳤다. 탭이 하는 일은 「무엇이 더 있는지」를 목록보다 * 먼저 보이게 하는 것이므로, 검사도 그것을 본다. */ function topic( slug: string, name: string, variantLabel: string, variants: ReadonlyArray<[string, string, string]>, ): PublicTopicDetail { return { name, slug, description: "", thesis: "", variantLabel, variants: variants.map(([variantSlug, title, conclusion]) => ({ slug: variantSlug, title, path: `/topics/${slug}/${variantSlug}`, summary: `${title} 요약`, conclusion, recordCount: 2, })), featuredCases: [], activeQuestions: [], relatedProjects: [], }; } const AUTH = topic("oauth-oidc-auth-boundary", "OAuth/OIDC 인증 경계", "구조", [ ["spa", "SPA", "브라우저가 token 을 들고 있다"], ["mediator", "Mediator", "교환만 서버가 맡는다"], ["bff", "BFF", "서버가 세션을 갖는다"], ["forward-auth", "Forward-Auth", "게이트웨이가 신원을 붙인다"], ]); const JPA = topic("jpa-feed-query-performance", "JPA 피드 조회 성능", "조회 전략", [ ["fetch-join", "Fetch Join", "행이 곱해진다"], ["derived-query", "Derived Query", "쿼리가 나뉜다"], ]); /** 목록이 주는 만큼. 탭은 상세 없이 이것만으로 그려져야 한다. */ function listItem(detail: PublicTopicDetail, recordCount: number): PublicTopic { return { name: detail.name, slug: detail.slug, thesis: "", description: "", variantLabel: detail.variantLabel, variantCount: detail.variants.length, recordCount, }; } function renderTabs( topics: ReadonlyArray, firstDetail: PublicTopicDetail, getTopicDetail = vi.fn(async (slug: string) => [AUTH, JPA].find((detail) => detail.slug === slug), ), ) { const techLog = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input; const application = createTestApplication({ featureInputs: { "tech-log": { ...techLog, publicContent: { ...techLog.publicContent, getTopicDetail }, }, }, }); render( renderWithQueryProviders( , ), ); return { getTopicDetail }; } const TABS = [listItem(AUTH, 18), listItem(JPA, 3)]; describe("홈의 주제 탭", () => { /* 이 검사가 답하는 것: 주제를 새로 만들면 코드를 고쳐야 탭이 느는가. 화면에는 주제 이름도, 개수도, 상한도 적혀 있지 않다. 탭은 목록이 준 것을 그대로 세우므로 서버가 셋을 주면 셋이 선다. 예전에 주제 화면이 주제 셋을 코드에 적어 두고 그 셋만 열던 때가 있었고, 새 주제를 만들어도 화면에는 나오지 않았다. */ it("주제가 늘면 코드를 고치지 않아도 탭이 는다", () => { const REDIS = topic("redis-adapter-ttl", "Redis 어댑터 TTL", "만료 전략", [ ["ttl", "TTL", "만료를 저장소가 맡는다"], ["sweep", "Sweep", "만료를 배치가 맡는다"], ]); renderTabs([...TABS, listItem(REDIS, 5)], AUTH); expect(screen.getAllByRole("tab").map((tab) => tab.textContent)).toEqual([ "OAuth/OIDC 인증 경계", "JPA 피드 조회 성능", "Redis 어댑터 TTL", ]); }); it("주제가 스무 개여도 전부 서고, 처음 여는 요청은 그대로 하나다", () => { const many = Array.from({ length: 20 }, (_, index) => listItem( topic(`topic-${index}`, `주제 ${index}`, "축", [ ["a", "A", ""], ["b", "B", ""], ]), index, ), ); const { getTopicDetail } = renderTabs([listItem(AUTH, 99), ...many], AUTH); expect(screen.getAllByRole("tab")).toHaveLength(21); expect(getTopicDetail).not.toHaveBeenCalled(); }); it("주제 이름이 목록보다 먼저 전부 보인다", () => { renderTabs(TABS, AUTH); expect(screen.getAllByRole("tab").map((tab) => tab.textContent)).toEqual([ "OAuth/OIDC 인증 경계", "JPA 피드 조회 성능", ]); }); it("첫 주제의 축은 미리 받아 둔 것으로 곧바로 열린다", () => { const { getTopicDetail } = renderTabs(TABS, AUTH); expect(getTopicDetail).not.toHaveBeenCalled(); const open = screen.getByRole("tabpanel"); expect(within(open).getAllByRole("link").map((link) => link.textContent)).toEqual([ "OAuth/OIDC 인증 경계 전체 보기", "SPA브라우저가 token 을 들고 있다", "Mediator교환만 서버가 맡는다", "BFF서버가 세션을 갖는다", "Forward-Auth게이트웨이가 신원을 붙인다", ]); expect(within(open).getByText("구조")).toBeTruthy(); }); it("고른 주제의 상세만 그때 받는다", async () => { const user = userEvent.setup(); const { getTopicDetail } = renderTabs(TABS, AUTH); await user.click(screen.getByRole("tab", { name: "JPA 피드 조회 성능" })); expect(getTopicDetail).toHaveBeenCalledExactlyOnceWith("jpa-feed-query-performance"); const open = screen.getByRole("tabpanel"); expect(within(open).getByText("조회 전략")).toBeTruthy(); await waitFor(() => expect( within(open) .getAllByRole("link") .map((link) => link.getAttribute("href")), ).toEqual([ "/topics/jpa-feed-query-performance", "/topics/jpa-feed-query-performance/fetch-join", "/topics/jpa-feed-query-performance/derived-query", ]), ); }); it("한 번 받은 주제는 다시 받지 않는다", async () => { const user = userEvent.setup(); const { getTopicDetail } = renderTabs(TABS, AUTH); await user.click(screen.getByRole("tab", { name: "JPA 피드 조회 성능" })); await screen.findByText("조회 전략"); await user.click(screen.getByRole("tab", { name: "OAuth/OIDC 인증 경계" })); await user.click(screen.getByRole("tab", { name: "JPA 피드 조회 성능" })); expect(getTopicDetail).toHaveBeenCalledOnce(); }); it("받지 못하면 그 자리에 남긴다 — 목록만 사라지지 않는다", async () => { const user = userEvent.setup(); renderTabs( TABS, AUTH, vi.fn(async () => { throw new Error("불통"); }), ); await user.click(screen.getByRole("tab", { name: "JPA 피드 조회 성능" })); expect(await screen.findByText("이 주제를 지금 불러오지 못했습니다.")).toBeTruthy(); expect(screen.getAllByRole("tab")).toHaveLength(2); }); it("방향키로 탭을 옮긴다", async () => { const user = userEvent.setup(); renderTabs(TABS, AUTH); await user.tab(); await user.keyboard("{ArrowRight}"); expect(screen.getByRole("tab", { selected: true }).textContent).toBe( "JPA 피드 조회 성능", ); }); it("주제가 하나면 고를 것이 없지만 목록은 그대로 나온다", () => { renderTabs([listItem(AUTH, 18)], AUTH); expect(screen.queryAllByRole("tab")).toHaveLength(0); expect(screen.getByRole("button").textContent).toBe("OAuth/OIDC 인증 경계"); expect( screen.getAllByRole("link").map((link) => link.getAttribute("href")), ).toEqual([ "/topics/oauth-oidc-auth-boundary", "/topics/oauth-oidc-auth-boundary/spa", "/topics/oauth-oidc-auth-boundary/mediator", "/topics/oauth-oidc-auth-boundary/bff", "/topics/oauth-oidc-auth-boundary/forward-auth", ]); }); });