Files
tech-log-frontend/tests/features/tech-log/public-document-screens.test.tsx
T
DongHyeonkaandClaude Opus 5 99c05c567d feat: 기록의 맥락을 읽기 난간의 앞뒤 한 칸으로 모은다
제목 아래 맥락 블록(ContextNavigator)과 난간의 Related 가 같은 것을 두 번
말하고 있었다. 난간 하나만 남기고, 거기에 주제가 정한 사고 순서의 바로
앞·뒤 한 칸을 둔다. 기록 화면은 그 순서를 알아야 하므로 자기 주제의 기록
목록을 함께 받는다.

주제의 사고 순서는 종류마다 한 편이 아니라 전부를 세우고, 관계가 가리키는
프로젝트 결정을 기준 다음 칸에 끼운다. 답이 나온 질문은 흐름에는 남되
「아직 답하지 못한 질문」으로 다시 서지 않는다.

문서 머리말의 빵부스러기는 프로젝트/주제만 남기고 종류는 링크가 아닌 한
줄로 내린다. 홈의 「종류별로 읽기」는 주 내비가 이미 데려가므로 내린다.

`tests/component/inline-line-breaks.test.tsx` 는 머리말의 `<p>` 를 전부
세고 있어서 종류 한 줄이 늘자 깨졌다. 요약만 세도록 좁혔다 — 문단 나누기를
망가뜨리면 여전히 실패한다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cfj8mZ9QmT3MEKonzM5xPj
2026-09-16 21:41:30 +09:00

452 lines
19 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen, within } from "@testing-library/react";
import { type ComponentType } from "react";
import {
createMemoryRouter,
Outlet,
RouterProvider,
} from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createTechLogFeatureInstalledInput } from "../../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../../helpers/studio-install-context.ts";
import {
TECH_LOG_ROUTE_REGISTRY,
TECH_LOG_ROUTE_RUNTIME_CONTRACT,
} from "../../../src/features/tech-log/contracts/tech-log-route-contract.ts";
import { CasePage } from "../../../src/features/tech-log/presentation/public/pages/case-page.tsx";
import { QuestionPage } from "../../../src/features/tech-log/presentation/public/pages/question-page.tsx";
import { ReferencePage } from "../../../src/features/tech-log/presentation/public/pages/reference-page.tsx";
import { TopicPage } from "../../../src/features/tech-log/presentation/public/pages/topic-page.tsx";
import { PublicNotFoundPage as NotFoundPage } from "../../../src/features/tech-log/presentation/public/pages/public-not-found-page.tsx";
import { PublicShell } from "../../../src/features/tech-log/presentation/public/public-shell.tsx";
import { TECH_LOG_ROUTE_CODECS } from "../../../src/features/tech-log/presentation/tech-log-route-codecs.ts";
import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx";
import { createGroupedRouteObjects } from "../../../src/presentation/routes/app-router.tsx";
import { PLATFORM_ROUTE_CODECS } from "../../../src/presentation/routes/platform-route-codecs.ts";
import { createTestApplication } from "../../helpers/create-test-application.ts";
import { renderWithQueryProviders } from "../../helpers/query-providers.tsx";
const routeCodecs = Object.freeze({
...PLATFORM_ROUTE_CODECS,
...TECH_LOG_ROUTE_CODECS,
});
const routeComponents = {
TECH_LOG_CASE: CasePage,
TECH_LOG_REFERENCE: ReferencePage,
TECH_LOG_QUESTION: QuestionPage,
TECH_LOG_TOPIC: TopicPage,
} as const satisfies Record<string, ComponentType>;
type DocumentRouteId = keyof typeof routeComponents;
/** 머리말이 거는 주제 링크를 확인하기 위한 픽스처의 이름 → slug 대응. */
const topicSlugs: Readonly<Record<string, string>> = {
JPA: "jpa",
Authentication: "authentication",
Redis: "redis",
};
class NoopIntersectionObserver implements IntersectionObserver {
readonly root = null;
readonly rootMargin = "0px";
readonly scrollMargin = "0px";
readonly thresholds = [0];
disconnect() {}
observe() {}
takeRecords(): IntersectionObserverEntry[] {
return [];
}
unobserve() {}
}
beforeEach(() => {
vi.stubGlobal("IntersectionObserver", NoopIntersectionObserver);
});
afterEach(() => {
vi.unstubAllGlobals();
});
async function renderDocumentRoute(routeId: DocumentRouteId, initialEntry: string) {
const definition = TECH_LOG_ROUTE_REGISTRY[routeId];
const runtime = TECH_LOG_ROUTE_RUNTIME_CONTRACT[routeId];
const Component = routeComponents[routeId];
const router = createMemoryRouter(
createGroupedRouteObjects(
{
[routeId]: definition,
NOT_FOUND: TECH_LOG_ROUTE_REGISTRY.NOT_FOUND,
},
{
[routeId]: { moduleId: runtime.moduleId, Component },
NOT_FOUND: {
moduleId: TECH_LOG_ROUTE_RUNTIME_CONTRACT.NOT_FOUND.moduleId,
Component: NotFoundPage,
},
},
{
PUBLIC: (
<PublicShell>
<Outlet />
</PublicShell>
),
STUDIO: <Outlet />,
},
"task-8-test-build",
routeCodecs,
),
{ initialEntries: [initialEntry] },
);
const techLog = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input;
const view = render(
renderWithQueryProviders(
<ApplicationProvider
application={createTestApplication({
featureInputs: { "tech-log": techLog },
})}
>
<RouterProvider router={router} />
</ApplicationProvider>,
));
// 포트가 async 가 되면서 첫 페인트에는 데이터가 없다. 화면이 정착한 뒤
// 단언하도록 여기서 한 번 기다린다 — 각 테스트에 흩어 놓으면 빠뜨린 곳이 생긴다.
await screen.findByRole("main");
return { ...view, router };
}
describe("TechLog canonical Public documents", () => {
it.each([
{
routeId: "TECH_LOG_CASE" as const,
path: "/cases/collection-fetch-join-pagination",
title: "컬렉션 Fetch Join과 페이징은 왜 충돌하는가",
kind: "검증 기록",
topic: "JPA",
project: "Backend Skeleton",
published: "2026.08.11",
evidence: "Join 결과 행 1,961개",
relations: [
"/questions/collection-fetch-join-with-pagination",
"/projects/backend-skeleton/decisions#feed-pagination-boundary",
"/references/jpa-list-fetch-strategy",
],
},
{
routeId: "TECH_LOG_CASE" as const,
path: "/cases/redis-adapter-ttl-boundary",
title: "Redis Adapter가 도메인 TTL 정책을 소유하지 않는 이유",
kind: "검증 기록",
topic: "Redis",
project: "Backend Skeleton",
published: "2026.08.07",
evidence: "정책과 저장 명령의 주인을 구분하기",
relations: [
"/projects/backend-skeleton",
"/projects/backend-skeleton/decisions#storage-port-unification",
],
},
{
routeId: "TECH_LOG_REFERENCE" as const,
path: "/references/state-and-nonce-boundary",
title: "Authorization Code Flow에서 state와 nonce의 경계",
kind: "적용 기준",
topic: "Authentication",
project: "Auth Lab",
published: "2026.08.09",
evidence: "state는 요청과 콜백을 연결합니다",
relations: [
"/questions/validate-edge-token-again",
"/projects/auth-lab",
],
},
{
routeId: "TECH_LOG_REFERENCE" as const,
path: "/references/jpa-list-fetch-strategy",
title: "JPA 목록 조회에서 Fetch 전략을 선택하는 기준",
kind: "적용 기준",
topic: "JPA",
project: "Backend Skeleton",
published: "2026.08.10",
evidence: "부모 페이지 경계를 먼저 고정합니다",
relations: [
"/cases/collection-fetch-join-pagination",
"/questions/collection-fetch-join-with-pagination",
],
},
{
routeId: "TECH_LOG_QUESTION" as const,
path: "/questions/validate-edge-token-again",
title: "oauth2-proxy가 전달한 토큰을 다시 검증해야 하는가?",
kind: "열린 질문",
topic: "Authentication",
project: "Auth Lab",
published: "2026.08.08",
evidence: "토큰 전달안과 신뢰 헤더안을 위협 모델로 비교하고",
relations: [
"/references/state-and-nonce-boundary",
"/projects/auth-lab/activity#edge-trust-boundary",
],
},
{
routeId: "TECH_LOG_QUESTION" as const,
path: "/questions/collection-fetch-join-with-pagination",
title: "컬렉션 Fetch Join을 유지하면서 페이징할 수 있는가?",
kind: "열린 질문",
topic: "JPA",
project: "Backend Skeleton",
published: "2026.08.05",
evidence: "해결 과정을 Case로 읽기",
relations: [
"/cases/collection-fetch-join-pagination",
"/references/jpa-list-fetch-strategy",
],
},
])(
"renders $path with exact metadata, evidence, and ordered relations",
async ({ routeId, path, title, kind, topic, project, published, evidence, relations }) => {
const { container } = await renderDocumentRoute(routeId, path);
const main = screen.getByRole("main");
expect(within(main).getByRole("heading", { level: 1, name: title })).toBeVisible();
/*
목차가 본문의 절 제목을 그대로 다시 적으므로 같은 글이 두 자리에 나온다. 여기서 확인하려는
것은 "그 글이 문서에 있는가" 이므로 첫 자리로 충분하다.
*/
const [firstEvidence] = within(main).getAllByText(evidence, { exact: false });
expect(firstEvidence).toBeVisible();
const breadcrumb = within(main).getByRole("navigation", { name: "문서 경로" });
expect(breadcrumb).toHaveTextContent(`${project}/${topic}`);
expect(breadcrumb).not.toHaveTextContent(kind);
const typeLabel = main.querySelector(
".case-header > .section-kicker, .public-document-header > .section-kicker",
);
expect(typeLabel).toHaveTextContent(kind);
/*
글자만 보고 있었더니 주제 링크가 어디로 가는지는 아무도 묻지 않았다. 그 링크는
`/topics/:slug` 를 가리켰고, 그 화면은 세 개의 주제를 하드코딩해 두고 있어 실제 주제는
무엇이든 404 였다 — 게시한 모든 문서가 죽은 링크를 하나씩 달고 있었다. 그동안은 탐색
필터로 우회했는데, 하드코딩이 없어졌으므로 이제 주제 화면으로 곧장 간다.
*/
expect(within(breadcrumb).getByRole("link", { name: topic })).toHaveAttribute(
"href",
`/topics/${topicSlugs[topic]}`,
);
/*
Case 는 한 배치를 쓴다. 예전에는 픽스처 문서 하나만 `.case-meta` 를 받고 나머지 Case 는
`.public-document-header dl` 로 떨어졌으므로 여기도 경로로 갈랐다. 이제 유형으로 가른다.
*/
if (kind === "검증 기록") {
expect(container.querySelector(".case-meta")).toHaveTextContent(`게시 ${published}`);
} else {
const metadata = container.querySelector(".public-document-header dl");
expect(metadata).toHaveTextContent(`유형${kind}`);
expect(metadata).toHaveTextContent(`프로젝트${project}`);
expect(metadata).toHaveTextContent(`게시${published}`);
}
expect(
Array.from(
container.querySelectorAll(".document-relations")[0]!.querySelectorAll("li a"),
(link) =>
link.getAttribute("href"),
),
).toEqual(relations);
},
);
it("preserves the specialized Fetch Join layout, TOC, rendered blocks, anchors, and evidence media", async () => {
const { container } = await renderDocumentRoute(
"TECH_LOG_CASE",
"/cases/collection-fetch-join-pagination",
);
const main = screen.getByRole("main");
expect(main).toHaveClass("case-page");
expect(main.querySelector("header.shell.case-header")).not.toBeNull();
expect(screen.getByRole("region", { name: "문제와 결론" })).toHaveTextContent(
"FeedItem 20건을 요청했지만",
);
expect(screen.getByText("Fetch 전략별 페이징 경계 관찰")).toBeVisible();
expect(screen.getByText("firstResult/maxResults specified with collection fetch; applying in memory")).toBeVisible();
expect(screen.getAllByText("MultipleBagFetchException")).toHaveLength(2);
expect(screen.getByRole("link", { name: "관찰한 값 바로가기" })).toHaveAttribute(
"href",
"#observed-values",
);
// 좁은 화면의 목차 하나. 넓은 화면의 레일은 「이 글에서」와 「맥락」으로 나뉜다.
expect(screen.getAllByRole("navigation", { name: "문서 목차" })).toHaveLength(1);
expect(screen.getByRole("navigation", { name: "이 글에서" })).toBeInTheDocument();
expect(container.querySelectorAll('[aria-label="코드 복사"]')).toHaveLength(3);
const image = screen.getByRole("img", {
name: "Fetch Join은 전체 조인 결과를 읽은 뒤 메모리에서 20개를 고르고, Batch Fetch는 부모 20개를 먼저 고른 뒤 해당 ID의 컬렉션만 조회한다.",
});
expect(image).toHaveAttribute("src", "/media/fetch-strategy-boundary.svg");
expect(image).toHaveAttribute("width", "1080");
expect(image).toHaveAttribute("height", "420");
expect(image).toHaveAttribute("loading", "lazy");
});
it("uses the one Case layout and omits source relations for the canonical empty state", async () => {
const generic = await renderDocumentRoute(
"TECH_LOG_CASE",
"/cases/redis-adapter-ttl-boundary",
);
expect(screen.getByRole("main")).toHaveClass("case-page");
expect(generic.container.querySelector("#ownership")).toHaveTextContent(
"정책과 저장 명령의 주인을 구분하기",
);
generic.unmount();
const empty = await renderDocumentRoute(
"TECH_LOG_CASE",
"/cases/collection-fetch-join-pagination?state=relations-empty",
);
expect(empty.container.querySelector(".document-relations")).toBeNull();
expect(screen.queryByText("Explicit relations")).not.toBeInTheDocument();
expect(screen.queryByRole("heading", { name: "다음에 읽을 것" })).not.toBeInTheDocument();
});
it("preserves Reference rule order and resolved Question evidence and empty copy", async () => {
const reference = await renderDocumentRoute(
"TECH_LOG_REFERENCE",
"/references/state-and-nonce-boundary",
);
expect(
Array.from(reference.container.querySelectorAll(".reference-rules h3"), (heading) =>
heading.textContent,
),
).toEqual([
"state는 요청과 콜백을 연결합니다",
"nonce는 인증 결과와 ID Token을 연결합니다",
"PKCE는 Code를 교환할 클라이언트를 증명합니다",
]);
expect(screen.getByText("마지막 검증 2026.08.09")).toBeVisible();
reference.unmount();
await renderDocumentRoute(
"TECH_LOG_QUESTION",
"/questions/collection-fetch-join-with-pagination",
);
expect(screen.getByText("RESOLVED")).toHaveClass(
"question-status",
"question-status--resolved",
);
expect(screen.getByText("해결 과정에서 남은 미지수가 없습니다.")).toBeVisible();
expect(screen.getByRole("link", { name: "해결 과정을 Case로 읽기" })).toHaveAttribute(
"href",
"/cases/collection-fetch-join-pagination",
);
});
});
describe("TechLog topics and Public not-found routing", () => {
it.each([
["jpa", "JPA"],
["authentication", "Authentication"],
["redis", "Redis"],
])("aggregates /topics/%s under its own name", async (slug, title) => {
await renderDocumentRoute("TECH_LOG_TOPIC", `/topics/${slug}`);
expect(screen.getByRole("heading", { level: 1, name: title })).toBeVisible();
expect(screen.getByRole("heading", { name: "정리된 개념과 기준" })).toBeVisible();
});
/*
주제 화면이 답하는 것은 "어떤 순서로 생각해서 여기까지 왔나" 다. 서버가 주는 대표 기록은
작성자가 주제마다 손으로 골라 두는 값이라 대부분 비어 있고, 비면 열린 질문만 남는다 —
아직 답이 없는 질문 넷을 모아 두고 흐름이라 부르는 것이 처음 온 사람에게 가장 나쁜 첫
화면이다. 그래서 기록에서 순서를 만든다: 원리 → 확인한 기록 → 기준.
아직 답하지 못한 질문은 흐름에 넣지 않는다. 마지막 칸에 두면 이 주제가 질문으로 끝난 것처럼
읽히고, 그것은 사고의 결과가 아니라 다음 할 일이다.
*/
it("separates Record reasoning flow from Knowledge and Open", async () => {
const { container } = await renderDocumentRoute("TECH_LOG_TOPIC", "/topics/jpa");
const steps = [...container.querySelectorAll(".context-flow__copy")].map((copy) => ({
label: copy.querySelector(".context-flow__meta")?.textContent,
href: copy.querySelector("a")?.getAttribute("href"),
}));
expect(steps.map((entry) => entry.label)).toEqual([
"검증 기록",
"열린 질문",
"적용 기준",
"결정",
]);
// Knowledge는 navigation의 나머지가 아니라 Topic에서 정리한 Concept / Reference 콘텐츠다.
const knowledge = [...container.querySelectorAll(".public-record-list > li > a")].map((link) =>
link.getAttribute("href"),
);
expect(knowledge).toContain("/references/jpa-list-fetch-strategy");
// 해결된 질문은 Reasoning Path에는 남아도 OPEN으로 다시 나타나지 않는다.
expect(screen.queryByRole("heading", { name: "아직 답하지 못한 질문" })).toBeNull();
});
/*
이 화면은 주제 셋을 코드에 적어 두고 그 셋만 열었다. 제목과 설명까지 코드에 있었고, 목록에
없는 주제는 기록이 멀쩡히 있어도 404 로 갔다 — 픽스처의 `kubernetes` 가 바로 그랬다.
계약에는 처음부터 `/topics/{slug}` 가 있었지만 아무도 부르지 않았다.
*/
it("opens a topic that was never in the hard-coded list", async () => {
await renderDocumentRoute("TECH_LOG_TOPIC", "/topics/kubernetes");
expect(screen.getByRole("heading", { level: 1, name: "Kubernetes" })).toBeVisible();
expect(
screen.queryByRole("heading", { name: "페이지를 찾을 수 없습니다." }),
).not.toBeInTheDocument();
});
it("keeps a sparse Topic useful when a Record leads directly to a Decision", async () => {
const { container } = await renderDocumentRoute("TECH_LOG_TOPIC", "/topics/redis");
expect(
Array.from(
container.querySelectorAll(".context-flow__copy > a"),
(link) => link.getAttribute("href"),
),
).toEqual([
"/cases/redis-adapter-ttl-boundary",
"/projects/backend-skeleton/decisions#storage-port-unification",
]);
});
it("keeps JPA topic records in canonical reasoning order", async () => {
const { container } = await renderDocumentRoute("TECH_LOG_TOPIC", "/topics/jpa");
expect(
Array.from(
container.querySelectorAll(".context-flow__copy > a"),
(link) => link.getAttribute("href"),
),
).toEqual([
"/cases/collection-fetch-join-pagination",
"/questions/collection-fetch-join-with-pagination",
"/references/jpa-list-fetch-strategy",
"/projects/backend-skeleton/decisions#feed-pagination-boundary",
]);
});
it.each([
["TECH_LOG_CASE" as const, "/cases/not-registered"],
["TECH_LOG_REFERENCE" as const, "/references/not-registered"],
["TECH_LOG_QUESTION" as const, "/questions/not-registered"],
["TECH_LOG_TOPIC" as const, "/topics/not-registered"],
])("keeps the unreachable client fallback accessible for %s", async (routeId, path) => {
const { container, router } = await renderDocumentRoute(routeId, path);
expect(router.state.location.pathname).toBe(path);
expect(
await screen.findByRole("heading", { name: "페이지를 찾을 수 없습니다." }),
).toBeVisible();
expect(screen.queryByRole("heading", { name: "화면을 표시하지 못했습니다." })).not.toBeInTheDocument();
expect(container.querySelector(".site-frame")).not.toBeNull();
});
});