chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the generator-built feature index with its app, bounded-context and feature declarations, the src/platform kernel and scale tooling, the 2026-09-24 src review fixes, and the 2026-09-25 maturity review round with its CHANGELOG [보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them merged with product changes; 127 are not carried. Product identity is unchanged: name, version 0.1.0, routes, design and the TechLog domain. Three decisions worth naming. TechLog stays composed directly, as the last two syncs recorded; its directory carries a NOT_INSTALLED marker that says so, and every installed-* composer takes the template's projection with TechLog added on top. The reference sample is no longer installed: the template now installs a feature only through feature-module.ts and context-routes.ts, which load the screens this product deleted, so its three operations, six schemas and one topic leave the registries, recorded as registry change evidence. And AppRouter mounts the platform and TechLog routes only; the template's bounded-context route gateway waits for a generator-installed feature. Required fixes: readSubject on the BFF session owner (without it every HTTP Studio session would close as integration-failed), zod through the facade in nine TechLog files, noUnusedLocals, and public/config.json written out to match the local profile. Derived baselines were recomputed after reproducing both sides' values: CI contract 101 commands / 106 references / 141 artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime config schema baseline equals the schema at8210d48. Verified here: types, lint, architecture, adapter inventory, CI contract, i18n, design system, diagnostics, browser security, dev release manifest, TechLog contract and build pass; 220 component, 155 integration, 15 contract, 418 TechLog, 43 reference-feature, 18 recipe and 46 release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at8210d48first and unchanged: check:registries (byte-identical), test:runtime-schema, verify:documentation. Brought by the template and escalated rather than suppressed: check:request-fanout on TechLog's cursor pagination, check:remediation-ledger (fails upstream too), the shared-chunk hash test, and the registry-dependent sample removal and second-feature tests. Playwright suites were not run. Full record, the five open questions and the follow-ups in docs/operations/template-sync-2026-09-29.md. (cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
This commit is contained in:
@@ -8,6 +8,10 @@ import {
|
||||
useApplicationMutation,
|
||||
} from "../../src/presentation/adapters/query/application-query.ts";
|
||||
import type { MutationIntentFactory } from "../../src/application/ports/mutation-intent-factory.ts";
|
||||
import { createFailure } from "../../src/contracts/errors.ts";
|
||||
import type { MutationIntent } from "../../src/contracts/mutation-intent.ts";
|
||||
import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts";
|
||||
import { MUTATION_COORDINATOR_BOUNDS } from "../../src/contracts/server-state.ts";
|
||||
import {
|
||||
RESOURCE_INVALIDATION_TOPIC,
|
||||
deterministicMutationIntentFactory,
|
||||
@@ -160,6 +164,62 @@ describe("application mutation intent admission", () => {
|
||||
await act(() => first);
|
||||
});
|
||||
|
||||
it("bounds JOIN_IDENTICAL waiters without starting another mutation", async () => {
|
||||
const client = queryClient();
|
||||
const scope = scopeSnapshot();
|
||||
let complete: (value: ApplicationResult<string>) => void = () => {};
|
||||
const execute = vi.fn(
|
||||
() =>
|
||||
new Promise<ApplicationResult<string>>((resolve) => {
|
||||
complete = resolve;
|
||||
}),
|
||||
);
|
||||
const hook = renderHook(
|
||||
() =>
|
||||
useApplicationMutation<string, string>({
|
||||
definitionId: "joined-waiter-budget-v1",
|
||||
definitionVersion: 1,
|
||||
operationId: "CREATE_JOINED_BOUNDED",
|
||||
requiresIdempotencyKey: true,
|
||||
owner: "platform-test",
|
||||
duplicatePolicy: "JOIN_IDENTICAL",
|
||||
scope,
|
||||
execute,
|
||||
invalidate: [],
|
||||
}),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
|
||||
let admitted: Promise<ApplicationResult<string>> | null = null;
|
||||
let joined: readonly Promise<ApplicationResult<string>>[] = [];
|
||||
let overflow: Promise<ApplicationResult<string>> | null = null;
|
||||
act(() => {
|
||||
admitted = hook.result.current.submit("same-input");
|
||||
joined = Array.from(
|
||||
{ length: MUTATION_COORDINATOR_BOUNDS.waitersPerJoinedIntent },
|
||||
() => hook.result.current.submit("same-input"),
|
||||
);
|
||||
overflow = hook.result.current.submit("same-input");
|
||||
});
|
||||
|
||||
expect(joined.every((waiter) => waiter === admitted)).toBe(true);
|
||||
expect(overflow).not.toBe(admitted);
|
||||
if (!overflow) throw new Error("expected overflow result");
|
||||
await expect(overflow).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "DUPLICATE_IN_FLIGHT",
|
||||
code: "JOIN_WAITER_LIMIT_EXCEEDED",
|
||||
effect: "NOT_STARTED",
|
||||
},
|
||||
});
|
||||
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
|
||||
|
||||
complete({ ok: true, value: "same-input" });
|
||||
if (!admitted) throw new Error("expected admitted mutation");
|
||||
await act(() => admitted);
|
||||
});
|
||||
|
||||
it("keeps the legacy raw mutation path outside the intent factory", async () => {
|
||||
const client = queryClient();
|
||||
const createIntent = vi.fn<MutationIntentFactory["create"]>();
|
||||
@@ -314,4 +374,124 @@ describe("application mutation intent admission", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("unknown-effect replay (D-1)", () => {
|
||||
function replayScope() {
|
||||
let token = 0;
|
||||
return {
|
||||
...scopeSnapshot(),
|
||||
identities: createRuntimeIdentityRegistry({
|
||||
tokenFactory: () => `replay-identity-token-${String(++token).padStart(4, "0")}`,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function renderKeyedCreate(
|
||||
outcomes: ApplicationResult<string>[],
|
||||
) {
|
||||
const client = queryClient();
|
||||
const intents: MutationIntent[] = [];
|
||||
const execute = vi.fn(
|
||||
async (
|
||||
input: string,
|
||||
context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>,
|
||||
): Promise<ApplicationResult<string>> => {
|
||||
intents.push(context.intent);
|
||||
return outcomes.shift() ?? { ok: true, value: input };
|
||||
},
|
||||
);
|
||||
const scope = replayScope();
|
||||
const hook = renderHook(
|
||||
() =>
|
||||
useApplicationMutation<string, string>({
|
||||
definitionId: "replay-intent-v1",
|
||||
definitionVersion: 1,
|
||||
operationId: "CREATE_REPLAYED",
|
||||
requiresIdempotencyKey: true,
|
||||
owner: "platform-test",
|
||||
duplicatePolicy: "REJECT_WHILE_ACTIVE",
|
||||
scope,
|
||||
execute,
|
||||
invalidate: [],
|
||||
}),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
return { hook, intents, execute };
|
||||
}
|
||||
|
||||
const unknown: ApplicationResult<string> = {
|
||||
ok: false,
|
||||
error: createFailure("SERVER_FAILURE", "CREATE_REPLAYED", 0, {
|
||||
effect: "MAYBE_APPLIED",
|
||||
}),
|
||||
};
|
||||
|
||||
it("sends the same intent when the same input is saved again after an unknown effect", async () => {
|
||||
const { hook, intents } = renderKeyedCreate([unknown]);
|
||||
await act(() => hook.result.current.submit("same-input"));
|
||||
expect(hook.result.current.state.indicator).toBe(
|
||||
"mutation-effect-unknown",
|
||||
);
|
||||
|
||||
await act(() => hook.result.current.submit("same-input"));
|
||||
|
||||
expect(intents).toHaveLength(2);
|
||||
expect(intents[1]).toBe(intents[0]);
|
||||
expect(intents[1]?.idempotencyKey).toBe("key-1");
|
||||
await waitFor(() =>
|
||||
expect(hook.result.current.state.indicator).toBeNull(),
|
||||
);
|
||||
});
|
||||
|
||||
it("mints a new key when the input changes after an unknown effect", async () => {
|
||||
const { hook, intents } = renderKeyedCreate([unknown]);
|
||||
await act(() => hook.result.current.submit("first-input"));
|
||||
await act(() => hook.result.current.submit("changed-input"));
|
||||
|
||||
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
|
||||
"key-1",
|
||||
"key-2",
|
||||
]);
|
||||
// The first request is still unresolved; a different request cannot
|
||||
// settle it.
|
||||
expect(hook.result.current.state.indicator).toBe(
|
||||
"mutation-effect-unknown",
|
||||
);
|
||||
});
|
||||
|
||||
it("resends the unknown head request with its original key", async () => {
|
||||
const { hook, intents, execute } = renderKeyedCreate([unknown, unknown]);
|
||||
await act(() => hook.result.current.submit("resent-input"));
|
||||
|
||||
let resent: ApplicationResult<string> | null | undefined;
|
||||
await act(async () => {
|
||||
resent = await hook.result.current.resendUnknownEffect();
|
||||
});
|
||||
expect(resent).toMatchObject({
|
||||
ok: false,
|
||||
error: { effect: "MAYBE_APPLIED" },
|
||||
});
|
||||
await act(async () => {
|
||||
resent = await hook.result.current.resendUnknownEffect();
|
||||
});
|
||||
|
||||
expect(resent).toEqual({ ok: true, value: "resent-input" });
|
||||
expect(execute.mock.calls.map(([input]) => input)).toEqual([
|
||||
"resent-input",
|
||||
"resent-input",
|
||||
"resent-input",
|
||||
]);
|
||||
expect(new Set(intents.map((intent) => intent.idempotencyKey))).toEqual(
|
||||
new Set(["key-1"]),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(hook.result.current.state.indicator).toBeNull(),
|
||||
);
|
||||
// Nothing is left to resend once the effect is settled.
|
||||
await act(async () => {
|
||||
resent = await hook.result.current.resendUnknownEffect();
|
||||
});
|
||||
expect(resent).toBeNull();
|
||||
expect(execute).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { onlineManager } from "@tanstack/react-query";
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -47,6 +48,130 @@ describe("application query inbound bridge", () => {
|
||||
expect(execute).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("coalesces repeated manual retries while stale data is refetching", async () => {
|
||||
const client = queryClient();
|
||||
const pending: Array<
|
||||
(value: ApplicationResult<string[]>) => void
|
||||
> = [];
|
||||
const execute = vi.fn(
|
||||
({ signal }: Readonly<{ signal: AbortSignal }>) => {
|
||||
if (execute.mock.calls.length === 1) {
|
||||
return Promise.resolve({ ok: true as const, value: ["first"] });
|
||||
}
|
||||
return new Promise<ApplicationResult<string[]>>((resolve) => {
|
||||
pending.push(resolve);
|
||||
signal.addEventListener(
|
||||
"abort",
|
||||
() => resolve({ ok: true, value: ["aborted"] }),
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
const hook = renderHook(
|
||||
() =>
|
||||
useApplicationQuery({
|
||||
queryKey: ["resource", "manual-retry-coalescing"],
|
||||
execute,
|
||||
}),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(hook.result.current.data).toEqual(["first"]));
|
||||
|
||||
let firstRetry: Promise<void> = Promise.resolve();
|
||||
act(() => {
|
||||
firstRetry = hook.result.current.retry();
|
||||
});
|
||||
await waitFor(() => expect(execute).toHaveBeenCalledTimes(2));
|
||||
|
||||
let secondRetry: Promise<void> = Promise.resolve();
|
||||
act(() => {
|
||||
secondRetry = hook.result.current.retry();
|
||||
});
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
const callsWhileActive = execute.mock.calls.length;
|
||||
const physicalRefetches = pending.length;
|
||||
act(() => {
|
||||
for (const resolve of pending) {
|
||||
resolve({ ok: true, value: ["recovered"] });
|
||||
}
|
||||
});
|
||||
await act(() => Promise.all([firstRetry, secondRetry]));
|
||||
await waitFor(() =>
|
||||
expect(hook.result.current.data).toEqual(["recovered"]),
|
||||
);
|
||||
|
||||
expect(callsWhileActive).toBe(2);
|
||||
expect(physicalRefetches).toBe(1);
|
||||
});
|
||||
|
||||
it("does not report a disabled query without data as loading", async () => {
|
||||
// A dependent query waiting on its prerequisite is idle, not loading.
|
||||
const client = queryClient();
|
||||
const execute = vi.fn(async () => ({ ok: true as const, value: ["x"] }));
|
||||
const hook = renderHook(
|
||||
() =>
|
||||
useApplicationQuery({
|
||||
queryKey: ["resource", "waiting-on-prerequisite"],
|
||||
execute,
|
||||
enabled: false,
|
||||
}),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
|
||||
expect(hook.result.current.state.base).toBe("idle");
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a completed query without items as empty, not idle", async () => {
|
||||
const client = queryClient();
|
||||
const hook = renderHook(
|
||||
() =>
|
||||
useApplicationQuery({
|
||||
queryKey: ["resource", "completed-empty"],
|
||||
execute: async () => ({ ok: true as const, value: [] as string[] }),
|
||||
}),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(hook.result.current.state.base).toBe("empty"));
|
||||
});
|
||||
|
||||
it("still reports a real first load as loading, including a paused offline one", async () => {
|
||||
const client = queryClient();
|
||||
const execute = vi.fn(
|
||||
() => new Promise<ApplicationResult<string[]>>(() => {}),
|
||||
);
|
||||
const inFlight = renderHook(
|
||||
() => useApplicationQuery({ queryKey: ["resource", "first"], execute }),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
|
||||
expect(inFlight.result.current.state.base).toBe("initial-loading");
|
||||
|
||||
// Offline, TanStack pauses the first fetch (isFetching=false) instead of
|
||||
// running it; the user is still waiting for data.
|
||||
onlineManager.setOnline(false);
|
||||
try {
|
||||
const paused = renderHook(
|
||||
() =>
|
||||
useApplicationQuery({ queryKey: ["resource", "offline"], execute }),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
expect(client.getQueryState(["resource", "offline"])?.fetchStatus).toBe(
|
||||
"paused",
|
||||
);
|
||||
expect(paused.result.current.state.base).toBe("initial-loading");
|
||||
} finally {
|
||||
onlineManager.setOnline(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("projects an initial application failure into terminal state", async () => {
|
||||
const client = queryClient();
|
||||
const failure = createFailure("FORBIDDEN", "LIST", 0);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { deriveAsyncState } from "../../src/application/view-models/async-state.ts";
|
||||
import { AsyncSurface } from "../../src/presentation/components/async-surface.tsx";
|
||||
import { createFailure } from "../../src/contracts/errors.ts";
|
||||
import { AccessSurface } from "../../src/presentation/design-system/index.ts";
|
||||
|
||||
describe("async UI state matrix", () => {
|
||||
it.each([
|
||||
@@ -14,6 +15,7 @@ describe("async UI state matrix", () => {
|
||||
[{ data: [{ id: "1" }] }, "success"],
|
||||
[{ data: [] }, "empty"],
|
||||
[{ data: null }, "empty"],
|
||||
[{}, "idle"],
|
||||
[
|
||||
{ failure: createFailure("SERVER_FAILURE", "LIST", 0) },
|
||||
"terminal-error",
|
||||
@@ -52,10 +54,11 @@ describe("async UI state matrix", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("renders unknown mutation effects with reconciliation-only actions", async () => {
|
||||
it("renders unknown mutation effects with confirm-applied and resend only", async () => {
|
||||
const user = userEvent.setup();
|
||||
const retry = vi.fn();
|
||||
const reconcile = vi.fn();
|
||||
const resend = vi.fn();
|
||||
const state = deriveAsyncState({
|
||||
data: ["value"],
|
||||
hasMutationEffectUnknown: true,
|
||||
@@ -66,6 +69,7 @@ describe("async UI state matrix", () => {
|
||||
state={state}
|
||||
onRetry={retry}
|
||||
onReconcileUnknownEffect={reconcile}
|
||||
onResendUnknownEffect={resend}
|
||||
>
|
||||
existing content
|
||||
</AsyncSurface>,
|
||||
@@ -80,12 +84,15 @@ describe("async UI state matrix", () => {
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "다시 시도" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "변경되지 않음으로 확인" }),
|
||||
).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "변경됨으로 확인" }));
|
||||
await user.click(
|
||||
screen.getByRole("button", { name: "변경되지 않음으로 확인" }),
|
||||
screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }),
|
||||
);
|
||||
expect(reconcile).toHaveBeenNthCalledWith(1, "APPLIED");
|
||||
expect(reconcile).toHaveBeenNthCalledWith(2, "NOT_APPLIED");
|
||||
expect(reconcile).toHaveBeenCalledExactlyOnceWith("APPLIED");
|
||||
expect(resend).toHaveBeenCalledOnce();
|
||||
expect(retry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -132,6 +139,17 @@ describe("async UI state matrix", () => {
|
||||
expect(resolveConflict).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
// 08-07. The id a user quotes when asking for help is the one the request
|
||||
// diagnostics carry as `correlation_id`.
|
||||
it("shows the failure's request id as its support reference", () => {
|
||||
const failure = {
|
||||
...createFailure("SERVER_FAILURE", "LIST", 1),
|
||||
requestId: "req-7f3a",
|
||||
};
|
||||
render(<AsyncSurface state={deriveAsyncState({ failure })} />);
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("지원 참조: req-7f3a");
|
||||
});
|
||||
|
||||
it("renders only safe error vocabulary", () => {
|
||||
const failure = createFailure("SERVER_FAILURE", "LIST", 0, {
|
||||
code: "SERVER_FAILURE",
|
||||
@@ -186,6 +204,71 @@ describe("async UI state matrix", () => {
|
||||
expect(action).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("renders an idle query as neither loading nor empty", () => {
|
||||
const { container, rerender } = render(
|
||||
<AsyncSurface state={deriveAsyncState({})}>content</AsyncSurface>,
|
||||
);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
|
||||
rerender(
|
||||
<AsyncSurface
|
||||
state={deriveAsyncState({})}
|
||||
idle={<p>조건을 먼저 선택하세요.</p>}
|
||||
>
|
||||
content
|
||||
</AsyncSurface>,
|
||||
);
|
||||
expect(screen.getByText("조건을 먼저 선택하세요.")).toBeVisible();
|
||||
expect(container.querySelector("[aria-busy]")).toBeNull();
|
||||
expect(screen.queryByText("표시할 항목이 없습니다.")).toBeNull();
|
||||
expect(screen.queryByText("content")).toBeNull();
|
||||
});
|
||||
|
||||
it("still renders loading for a first load and the empty copy for an empty result", () => {
|
||||
const { container, rerender } = render(
|
||||
<AsyncSurface state={deriveAsyncState({ isInitialLoading: true })} />,
|
||||
);
|
||||
expect(container.querySelector('[aria-busy="true"]')).not.toBeNull();
|
||||
|
||||
rerender(<AsyncSurface state={deriveAsyncState({ data: [] })} />);
|
||||
expect(screen.getByText("표시할 항목이 없습니다.")).toBeVisible();
|
||||
});
|
||||
|
||||
// 08-11. A query failure and the gallery draw one access set, not two.
|
||||
it.each([
|
||||
["AUTH_REQUIRED", "auth-required"],
|
||||
["FORBIDDEN", "forbidden"],
|
||||
["NOT_FOUND", "not-found"],
|
||||
] as const)(
|
||||
"renders a %s query failure with the gallery's access surface",
|
||||
async (kind, accessKind) => {
|
||||
const user = userEvent.setup();
|
||||
const action = vi.fn();
|
||||
const failure = createFailure(kind, "LIST", 0);
|
||||
const gallery = render(
|
||||
<AccessSurface kind={accessKind} onAction={() => {}} />,
|
||||
);
|
||||
const expected = gallery.container.querySelector(".state-surface");
|
||||
expect(expected).not.toBeNull();
|
||||
const expectedText = expected?.textContent;
|
||||
gallery.unmount();
|
||||
|
||||
render(
|
||||
<AsyncSurface
|
||||
state={deriveAsyncState({ failure })}
|
||||
onAction={action}
|
||||
/>,
|
||||
);
|
||||
const alert = screen.getByRole("alert");
|
||||
expect(alert).toHaveAttribute("data-message-key", failure.userMessageKey);
|
||||
expect(alert.querySelector(".state-surface")?.textContent).toBe(
|
||||
expectedText,
|
||||
);
|
||||
await user.click(screen.getByRole("button"));
|
||||
expect(action).toHaveBeenCalledOnce();
|
||||
},
|
||||
);
|
||||
|
||||
it("does not retain a terminal error after usable data is restored", () => {
|
||||
const failed = deriveAsyncState({
|
||||
failure: createFailure("SERVER_FAILURE", "LIST", 0),
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
// 09-03. A throw while the feature graph evaluates (a duplicate message key,
|
||||
// a route or operation conflict) used to stop main.tsx before boot() ran, so
|
||||
// the static "loading" shell stayed up forever.
|
||||
vi.mock("../../src/.generated/product-feature-index.ts", () => {
|
||||
throw new TypeError("Duplicate ko-KR message key: probe.title");
|
||||
});
|
||||
|
||||
describe("boot entry (09-03)", () => {
|
||||
it("shows the boot error shell when the app graph fails to evaluate", async () => {
|
||||
document.body.innerHTML =
|
||||
'<div id="root"><div role="status" data-boot-shell="">불러오는 중</div></div>';
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
|
||||
await import("../../src/bootstrap/main.tsx");
|
||||
|
||||
const shell = await screen.findByRole("alert", undefined, { timeout: 5_000 });
|
||||
expect(shell).toHaveTextContent("애플리케이션을 시작할 수 없습니다.");
|
||||
expect(document.querySelector("[data-boot-shell]")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx";
|
||||
|
||||
// 09-04. An assembly defect (here the TypeError a missing feature capability
|
||||
// used to produce) was shown as BOOT_CONFIG_FAILURE and the error was dropped.
|
||||
const assemblyDefect = new TypeError(
|
||||
"Cannot read properties of undefined (reading 'get')",
|
||||
);
|
||||
vi.mock("../../src/bootstrap/create-runtime-composition.ts", () => ({
|
||||
createRuntimeComposition: async () => {
|
||||
throw assemblyDefect;
|
||||
},
|
||||
}));
|
||||
|
||||
describe("unexpected boot failure (09-04)", () => {
|
||||
it("is shown as BOOT_UNEXPECTED_FAILURE and reports the error in development", async () => {
|
||||
document.body.innerHTML =
|
||||
'<div id="root"><div role="status" data-boot-shell="">불러오는 중</div></div>';
|
||||
// jsdom has no reportError; browsers do.
|
||||
const reportError = vi.fn<(error: unknown) => void>();
|
||||
vi.stubGlobal("reportError", reportError);
|
||||
|
||||
await import("../../src/bootstrap/main.tsx");
|
||||
|
||||
const shell = await screen.findByRole("alert", undefined, { timeout: 5_000 });
|
||||
expect(shell).toHaveTextContent("BOOT_UNEXPECTED_FAILURE");
|
||||
expect(shell).not.toHaveTextContent("BOOT_CONFIG_FAILURE");
|
||||
expect(shell).toHaveTextContent("local-build");
|
||||
expect(shell).toHaveTextContent("TypeError");
|
||||
expect(shell).not.toHaveTextContent("reading 'get'");
|
||||
expect(reportError).toHaveBeenCalledWith(assemblyDefect);
|
||||
});
|
||||
|
||||
it("lists the rejected configuration keys", () => {
|
||||
const view = render(
|
||||
<BootErrorShell
|
||||
kind="BOOT_CONFIG_FAILURE"
|
||||
code="CONFIG_SCHEMA_INVALID"
|
||||
buildId="build-a"
|
||||
invalidKeys={["TELEMETRY_ENABELD"]}
|
||||
supportReference="build-a:CONFIG_SCHEMA_INVALID"
|
||||
/>,
|
||||
);
|
||||
const shell = within(view.container).getByRole("alert");
|
||||
expect(within(shell).getByText("잘못된 설정 키")).toBeInTheDocument();
|
||||
expect(shell).toHaveTextContent("TELEMETRY_ENABELD");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
function TestShell() {
|
||||
@@ -15,3 +18,35 @@ describe("component test level", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("static boot shell (Q-6.9-8)", () => {
|
||||
function loadIndexBody(): HTMLElement {
|
||||
const html = readFileSync("index.html", "utf8");
|
||||
document.body.innerHTML = new DOMParser()
|
||||
.parseFromString(html, "text/html")
|
||||
.body.innerHTML;
|
||||
const root = document.getElementById("root");
|
||||
if (!root) throw new Error("index.html has no #root");
|
||||
return root;
|
||||
}
|
||||
|
||||
it("shows a busy loading status before boot renders anything", () => {
|
||||
const root = loadIndexBody();
|
||||
const status = root.querySelector('[role="status"]');
|
||||
expect(status?.getAttribute("aria-busy")).toBe("true");
|
||||
expect(status?.textContent?.trim()).not.toBe("");
|
||||
});
|
||||
|
||||
it("is replaced by the first render of the real app", async () => {
|
||||
const root = loadIndexBody();
|
||||
const reactRoot = createRoot(root);
|
||||
await act(async () => {
|
||||
reactRoot.render(<TestShell />);
|
||||
});
|
||||
expect(root.querySelector('[aria-busy="true"]')).toBeNull();
|
||||
expect(screen.getByRole("main", { name: "application shell" })).toBeTruthy();
|
||||
await act(async () => {
|
||||
reactRoot.unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { lazy, Suspense } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -8,6 +10,25 @@ import {
|
||||
isChunkLoadFailure,
|
||||
} from "../../src/presentation/boundaries/chunk-recovery-boundary.tsx";
|
||||
import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx";
|
||||
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
|
||||
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
|
||||
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
|
||||
import { createTestApplication } from "../helpers/create-test-application.ts";
|
||||
import { createTechLogFeatureInstalledInput } from "../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
|
||||
import { renderWithQueryProviders } from "../helpers/query-providers.tsx";
|
||||
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../helpers/studio-install-context.ts";
|
||||
|
||||
// The Explore page stands in for a route chunk the network could not deliver:
|
||||
// a rejected lazy module throws its rejection on every render, as this does
|
||||
// (template sync af3d8e6: upstream uses its states example page, which this
|
||||
// product deleted).
|
||||
vi.mock("../../src/features/tech-log/presentation/public/pages/explore-page.tsx", () => ({
|
||||
ExplorePage: function UnreachableChunk(): never {
|
||||
throw new TypeError(
|
||||
"Failed to fetch dynamically imported module: /assets/explore.js",
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
function ChunkDefect(): never {
|
||||
throw new TypeError("Failed to fetch dynamically imported module");
|
||||
@@ -27,6 +48,47 @@ describe("chunk recovery boundary classification", () => {
|
||||
expect(isChunkLoadFailure(new Error("ordinary render defect"))).toBe(false);
|
||||
});
|
||||
|
||||
it("recognizes the WebKit module failure and the Vite CSS preload failure", () => {
|
||||
expect(
|
||||
isChunkLoadFailure(new TypeError("Importing a module script failed.")),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isChunkLoadFailure(
|
||||
new Error("Unable to preload CSS for /assets/states-3f2a.css"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("recovers when Vite rethrows a vite:preloadError into the lazy import", async () => {
|
||||
// Vite dispatches `vite:preloadError` and, unless a listener prevents it,
|
||||
// rejects the dynamic import with the same error. That rejection is what
|
||||
// reaches this boundary.
|
||||
const Page = lazy(() =>
|
||||
Promise.reject(new Error("Unable to preload CSS for /assets/states.css")),
|
||||
);
|
||||
const recover = vi.fn(async () => ({
|
||||
action: "support" as const,
|
||||
reason: "reload-already-attempted",
|
||||
}));
|
||||
render(
|
||||
<Suspense fallback={null}>
|
||||
<ChunkRecoveryBoundary chunkId="route-states" recover={recover}>
|
||||
<Page />
|
||||
</ChunkRecoveryBoundary>
|
||||
</Suspense>,
|
||||
);
|
||||
|
||||
expect(
|
||||
await screen.findByRole("heading", {
|
||||
name: "화면 자산을 복구하지 못했습니다.",
|
||||
}),
|
||||
).toBeVisible();
|
||||
expect(recover).toHaveBeenCalledWith({
|
||||
chunkId: "route-states",
|
||||
failureKind: "CHUNK_LOAD_FAILURE",
|
||||
});
|
||||
});
|
||||
|
||||
it("runs the recovery input only for a lazy chunk rejection", async () => {
|
||||
const recover = vi.fn(async () => ({
|
||||
action: "support" as const,
|
||||
@@ -65,4 +127,99 @@ describe("chunk recovery boundary classification", () => {
|
||||
);
|
||||
expect(recover).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("offers a user-started reload on the failure surface", async () => {
|
||||
render(
|
||||
<ChunkRecoveryBoundary
|
||||
chunkId="route-home"
|
||||
recover={async () => ({
|
||||
action: "support" as const,
|
||||
reason: "reload-already-attempted",
|
||||
})}
|
||||
>
|
||||
<ChunkDefect />
|
||||
</ChunkRecoveryBoundary>,
|
||||
);
|
||||
|
||||
expect(
|
||||
await screen.findByRole("button", { name: "한 번 새로고침" }),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
// 08-07. An unrecovered chunk failure shows a reference the render
|
||||
// diagnostic also records.
|
||||
it("shows an unrecovered chunk failure's support reference and records it", async () => {
|
||||
const record = vi.fn();
|
||||
window.history.pushState({}, "", "/explore");
|
||||
render(
|
||||
renderWithQueryProviders(
|
||||
<ApplicationProvider
|
||||
application={createTestApplication({
|
||||
diagnostics: { record },
|
||||
featureInputs: {
|
||||
"tech-log": createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input,
|
||||
},
|
||||
})}
|
||||
>
|
||||
<PreferenceProviders>
|
||||
<AppRouter buildId="build-a" />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/);
|
||||
const incidentId = reference.textContent?.split(":").at(-1);
|
||||
expect(record).toHaveBeenCalledWith({
|
||||
level: "error",
|
||||
eventId: "ui.render.failed",
|
||||
context: expect.objectContaining({
|
||||
route_id: "TECH_LOG_EXPLORE",
|
||||
build_id: "build-a",
|
||||
correlation_id: incidentId,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("clears a failed route chunk when the user moves to a sibling route", async () => {
|
||||
// React Router reuses the rendered-route instance between sibling routes,
|
||||
// so a failure latched in one route's boundary would otherwise follow the
|
||||
// user to every other page until a full reload.
|
||||
const user = userEvent.setup();
|
||||
window.history.pushState({}, "", "/explore");
|
||||
render(
|
||||
renderWithQueryProviders(
|
||||
<ApplicationProvider
|
||||
application={createTestApplication({
|
||||
featureInputs: {
|
||||
"tech-log": createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input,
|
||||
},
|
||||
})}
|
||||
>
|
||||
<PreferenceProviders>
|
||||
<AppRouter />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
expect(
|
||||
await screen.findByRole("heading", {
|
||||
name: "화면 자산을 복구하지 못했습니다.",
|
||||
}),
|
||||
).toBeVisible();
|
||||
|
||||
await user.click(screen.getAllByRole("link", { name: "주제" })[0]!);
|
||||
|
||||
expect(
|
||||
await screen.findByRole(
|
||||
"heading",
|
||||
{ name: "주제", level: 1 },
|
||||
{ timeout: 5000 },
|
||||
),
|
||||
).toBeVisible();
|
||||
expect(
|
||||
screen.queryByRole("heading", { name: "화면 자산을 복구하지 못했습니다." }),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import type { ReactNode } from "react";
|
||||
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
Breadcrumbs,
|
||||
LinkButton,
|
||||
Pagination,
|
||||
} from "../../src/presentation/design-system/index.ts";
|
||||
import { StandardPage } from "../../src/presentation/templates/index.ts";
|
||||
|
||||
function LocationProbe() {
|
||||
const location = useLocation();
|
||||
return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;
|
||||
}
|
||||
|
||||
function renderInRouter(ui: ReactNode, entry = "/app/items?q=term&sort=name") {
|
||||
return render(
|
||||
<MemoryRouter basename="/app" initialEntries={[entry]}>
|
||||
<Routes>
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
<>
|
||||
{ui}
|
||||
<LocationProbe />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("design-system links inside the router", () => {
|
||||
it("renders LinkButton `to` as a router link that keeps the basename", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderInRouter(<LinkButton to="/examples/states">States</LinkButton>);
|
||||
|
||||
const link = screen.getByRole("link", { name: "States" });
|
||||
expect(link).toHaveAttribute("href", "/app/examples/states");
|
||||
expect(link).toHaveClass("ui-button", "ui-button--primary");
|
||||
|
||||
await user.click(link);
|
||||
expect(screen.getByTestId("location")).toHaveTextContent(
|
||||
/^\/examples\/states$/,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps LinkButton `href` as a plain anchor", () => {
|
||||
renderInRouter(<LinkButton href="https://example.com/docs">Docs</LinkButton>);
|
||||
expect(screen.getByRole("link", { name: "Docs" })).toHaveAttribute(
|
||||
"href",
|
||||
"https://example.com/docs",
|
||||
);
|
||||
});
|
||||
|
||||
it("renders breadcrumb `to` items as router links", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderInRouter(
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: "Home", to: "/" },
|
||||
{ label: "Examples", to: "/examples" },
|
||||
{ label: "States" },
|
||||
]}
|
||||
label="Location"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Home" })).toHaveAttribute(
|
||||
"href",
|
||||
"/app",
|
||||
);
|
||||
await user.click(screen.getByRole("link", { name: "Examples" }));
|
||||
expect(screen.getByTestId("location")).toHaveTextContent(/^\/examples$/);
|
||||
expect(screen.getByText("States")).toHaveAttribute("aria-current", "page");
|
||||
});
|
||||
|
||||
it("renders page link actions with `to` as router links", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderInRouter(
|
||||
<StandardPage
|
||||
actions={[
|
||||
{ kind: "link", label: "Open states", to: "/examples/states" },
|
||||
{ kind: "link", label: "External", href: "https://example.com" },
|
||||
]}
|
||||
heading={{ title: "Page" }}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "External" })).toHaveAttribute(
|
||||
"href",
|
||||
"https://example.com",
|
||||
);
|
||||
const link = screen.getByRole("link", { name: "Open states" });
|
||||
expect(link).toHaveAttribute("href", "/app/examples/states");
|
||||
await user.click(link);
|
||||
expect(screen.getByTestId("location")).toHaveTextContent(
|
||||
/^\/examples\/states$/,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the other search parameters and the basename in pagination links", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
renderInRouter(
|
||||
<Pagination
|
||||
label="Pages"
|
||||
nextLabel="Next"
|
||||
onChange={onChange}
|
||||
page={1}
|
||||
pageCount={3}
|
||||
pageLabel={(page) => `Page ${page}`}
|
||||
previousLabel="Previous"
|
||||
/>,
|
||||
"/app/items?q=term&sort=name&page=1",
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Page 2" })).toHaveAttribute(
|
||||
"href",
|
||||
"/app/items?q=term&sort=name&page=2",
|
||||
);
|
||||
await user.click(screen.getByRole("link", { name: "Page 3" }));
|
||||
expect(onChange).toHaveBeenCalledWith(3);
|
||||
// Page changes stay with the owner: the link itself does not navigate.
|
||||
expect(screen.getByTestId("location")).toHaveTextContent(
|
||||
"/items?q=term&sort=name&page=1",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pagination outside a router", () => {
|
||||
it("keeps the other search parameters of the document URL", () => {
|
||||
window.history.pushState({}, "", "/list?q=term");
|
||||
render(
|
||||
<Pagination
|
||||
label="Pages"
|
||||
nextLabel="Next"
|
||||
onChange={() => {}}
|
||||
page={1}
|
||||
pageCount={2}
|
||||
pageLabel={(page) => `Page ${page}`}
|
||||
previousLabel="Previous"
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByRole("link", { name: "Page 2" })).toHaveAttribute(
|
||||
"href",
|
||||
"?q=term&page=2",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -23,12 +23,41 @@ import {
|
||||
Pagination,
|
||||
Popover,
|
||||
RadioGroup,
|
||||
SearchField,
|
||||
Switch,
|
||||
Tabs,
|
||||
ToastProvider,
|
||||
useToast,
|
||||
} from "../../src/presentation/design-system/index.ts";
|
||||
|
||||
describe("SearchField", () => {
|
||||
it("returns focus to the input when the clear button removes itself", async () => {
|
||||
const user = userEvent.setup();
|
||||
function ControlledSearch() {
|
||||
const [value, setValue] = useState("query");
|
||||
return (
|
||||
<SearchField
|
||||
clearLabel="Clear search"
|
||||
label="Search"
|
||||
onChange={(event) => setValue(event.currentTarget.value)}
|
||||
onClear={() => setValue("")}
|
||||
value={value}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(<ControlledSearch />);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Clear search" }));
|
||||
|
||||
const input = screen.getByRole("searchbox", { name: "Search" });
|
||||
expect(input).toHaveValue("");
|
||||
expect(input).toHaveFocus();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Clear search" }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("design-system platform interactions", () => {
|
||||
it("keeps decorative icons out of the accessibility tree and names icon actions", () => {
|
||||
render(
|
||||
@@ -150,6 +179,40 @@ describe("design-system platform interactions", () => {
|
||||
await waitFor(() => expect(trigger).toHaveFocus());
|
||||
});
|
||||
|
||||
it("does not pull back focus that moved out of a closed drawer", async () => {
|
||||
// A route change focuses the new page in the same tick the drawer closes;
|
||||
// the drawer's deferred restore must not take that focus back.
|
||||
const user = userEvent.setup();
|
||||
function Harness() {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<Button onClick={() => setOpen(true)}>탐색 열기</Button>
|
||||
<h1 tabIndex={-1}>새 페이지</h1>
|
||||
<Drawer onClose={() => setOpen(false)} open={open} title="탐색">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
queueMicrotask(() =>
|
||||
screen.getByRole("heading", { name: "새 페이지" }).focus(),
|
||||
);
|
||||
}}
|
||||
>
|
||||
이동
|
||||
</Button>
|
||||
</Drawer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
render(<Harness />);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "탐색 열기" }));
|
||||
await user.click(screen.getByRole("button", { name: "이동" }));
|
||||
await act(() => new Promise((resolve) => setTimeout(resolve, 20)));
|
||||
|
||||
expect(screen.getByRole("heading", { name: "새 페이지" })).toHaveFocus();
|
||||
});
|
||||
|
||||
it("bounds the toast queue and collapses duplicate IDs", async () => {
|
||||
const user = userEvent.setup();
|
||||
function Harness() {
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
DirtyNavigationDialog,
|
||||
ErrorSummary,
|
||||
Form,
|
||||
FormFailureStatus,
|
||||
FormField,
|
||||
useAppForm,
|
||||
useDirtyNavigationGuard,
|
||||
@@ -34,6 +35,7 @@ function FormHarness(props: Readonly<{
|
||||
| Readonly<{ ok: false; error: ReturnType<typeof createFailure> }>
|
||||
>;
|
||||
resetOnSuccess?: boolean;
|
||||
onFailureAction?(): void;
|
||||
}>) {
|
||||
const form = useAppForm({
|
||||
schema,
|
||||
@@ -57,6 +59,14 @@ function FormHarness(props: Readonly<{
|
||||
fieldId={form.fieldId}
|
||||
onFocusField={form.focusField}
|
||||
/>
|
||||
<FormFailureStatus
|
||||
failure={form.failure}
|
||||
onAction={
|
||||
form.result === "retry-later"
|
||||
? () => void form.submitForm()
|
||||
: props.onFailureAction
|
||||
}
|
||||
/>
|
||||
<FormField {...form.field("name")} label="Name" required />
|
||||
<FormField {...form.field("note")} label="Note" />
|
||||
<Button type="submit" disabled={form.pending}>
|
||||
@@ -137,6 +147,96 @@ describe("local form facade", () => {
|
||||
expect(document.body).not.toHaveTextContent("raw-secret-message");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"AUTH_REQUIRED",
|
||||
"reauth-required",
|
||||
"계속하려면 로그인이 필요합니다.",
|
||||
"로그인",
|
||||
],
|
||||
[
|
||||
"FORBIDDEN",
|
||||
"forbidden",
|
||||
"이 작업을 수행할 권한이 없습니다.",
|
||||
"안전한 화면으로 이동",
|
||||
],
|
||||
[
|
||||
"RATE_LIMITED",
|
||||
"retry-later",
|
||||
"요청이 많습니다. 잠시 후 다시 시도해 주세요.",
|
||||
"다시 시도",
|
||||
],
|
||||
] as const)(
|
||||
"shows %s as its own save state, not an input error",
|
||||
async (kind, result, copy, action) => {
|
||||
const user = userEvent.setup();
|
||||
const onFailureAction = vi.fn();
|
||||
const submit = vi.fn(async () => ({
|
||||
ok: false as const,
|
||||
error: createFailure(kind, "CREATE_ENTITY", 0, {
|
||||
effect: "NOT_APPLIED",
|
||||
}),
|
||||
}));
|
||||
render(
|
||||
<FormHarness submit={submit} onFailureAction={onFailureAction} />,
|
||||
);
|
||||
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
|
||||
await user.click(screen.getByRole("button", { name: "Submit" }));
|
||||
|
||||
expect(await screen.findByTestId("result")).toHaveTextContent(result);
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(copy);
|
||||
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
|
||||
expect(document.body).not.toHaveTextContent("저장하지 못했습니다.");
|
||||
expect(
|
||||
document.body.textContent?.includes("입력한 내용은 사라집니다"),
|
||||
).toBe(kind === "AUTH_REQUIRED");
|
||||
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Valid");
|
||||
|
||||
await user.click(screen.getByRole("button", { name: action }));
|
||||
if (kind === "RATE_LIMITED") {
|
||||
expect(submit).toHaveBeenCalledTimes(2);
|
||||
expect(onFailureAction).not.toHaveBeenCalled();
|
||||
} else {
|
||||
expect(onFailureAction).toHaveBeenCalledOnce();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// F-10 (08-01). A save that failed for a reason the user cannot fix in the
|
||||
// input is a status with its own action, never an input error summary.
|
||||
it.each([
|
||||
["NOT_FOUND", "요청한 항목을 찾을 수 없습니다.", "안전한 화면으로 이동"],
|
||||
// This product's catalog copy (the template says "요청을 처리할 수 없습니다.").
|
||||
["UNKNOWN_CLIENT_FAILURE", "요청을 처리하지 못했습니다.", "지원 정보 확인"],
|
||||
] as const)(
|
||||
"shows an unavailable %s save as a status, not an input error",
|
||||
async (kind, copy, action) => {
|
||||
const user = userEvent.setup();
|
||||
const onFailureAction = vi.fn();
|
||||
render(
|
||||
<FormHarness
|
||||
submit={async () => ({
|
||||
ok: false,
|
||||
error: createFailure(kind, "CREATE_ENTITY", 0, {
|
||||
effect: "NOT_APPLIED",
|
||||
}),
|
||||
})}
|
||||
onFailureAction={onFailureAction}
|
||||
/>,
|
||||
);
|
||||
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
|
||||
await user.click(screen.getByRole("button", { name: "Submit" }));
|
||||
|
||||
expect(await screen.findByTestId("result")).toHaveTextContent(
|
||||
"unavailable",
|
||||
);
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(copy);
|
||||
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
|
||||
await user.click(screen.getByRole("button", { name: action }));
|
||||
expect(onFailureAction).toHaveBeenCalledOnce();
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps conflict input out of URL and storage", async () => {
|
||||
const user = userEvent.setup();
|
||||
localStorage.clear();
|
||||
@@ -278,3 +378,92 @@ describe("dirty navigation guard", () => {
|
||||
expect(await screen.findByRole("heading", { name: "Target" })).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
describe("submission timing", () => {
|
||||
it("submits once when a second submit arrives during async validation", async () => {
|
||||
const user = userEvent.setup();
|
||||
let releaseValidation: () => void = () => {};
|
||||
const validationGate = new Promise<void>((resolve) => {
|
||||
releaseValidation = resolve;
|
||||
});
|
||||
const asyncSchema = schema.refine(async () => {
|
||||
await validationGate;
|
||||
return true;
|
||||
});
|
||||
const submit = vi.fn(async () => ({ ok: true as const, value: "saved" }));
|
||||
|
||||
function AsyncForm() {
|
||||
const form = useAppForm({
|
||||
schema: asyncSchema,
|
||||
defaultValues: defaults,
|
||||
allowedServerFields: ["name", "note"],
|
||||
mapToCommand: (values) => ({ name: values.name }),
|
||||
submit,
|
||||
});
|
||||
return (
|
||||
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
|
||||
<FormField {...form.field("name")} label="Name" required />
|
||||
<Button type="submit">Submit</Button>
|
||||
<output data-testid="result">{form.result}</output>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
render(<AsyncForm />);
|
||||
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready");
|
||||
await user.click(screen.getByRole("button", { name: "Submit" }));
|
||||
await user.click(screen.getByRole("button", { name: "Submit" }));
|
||||
releaseValidation();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId("result")).toHaveTextContent("success"),
|
||||
);
|
||||
expect(submit).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not ask to discard changes when navigating right after a save", async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
function SaveThenLeave() {
|
||||
const navigate = useNavigate();
|
||||
const form = useAppForm({
|
||||
schema,
|
||||
defaultValues: defaults,
|
||||
allowedServerFields: ["name", "note"],
|
||||
mapToCommand: (values) => ({ name: values.name }),
|
||||
submit: async () => ({ ok: true as const, value: "saved" }),
|
||||
});
|
||||
const guard = useDirtyNavigationGuard(form.dirty);
|
||||
return (
|
||||
<Form
|
||||
onSubmit={(event) => {
|
||||
void form.submitForm(event).then((outcome) => {
|
||||
if (outcome?.ok) void navigate("/done");
|
||||
});
|
||||
}}
|
||||
pending={form.pending}
|
||||
>
|
||||
<FormField {...form.field("name")} label="Name" required />
|
||||
<Button type="submit">Save</Button>
|
||||
<DirtyNavigationDialog guard={guard} />
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
const router = createMemoryRouter(
|
||||
[
|
||||
{ path: "/", element: <SaveThenLeave /> },
|
||||
{ path: "/done", element: <h1>Done</h1> },
|
||||
],
|
||||
{ initialEntries: ["/"] },
|
||||
);
|
||||
render(<RouterProvider router={router} />);
|
||||
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
|
||||
expect(await screen.findByRole("heading", { name: "Done" })).toBeVisible();
|
||||
expect(
|
||||
screen.queryByRole("dialog", { name: "저장하지 않은 변경이 있습니다." }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { useState } from "react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
Button,
|
||||
@@ -16,6 +17,15 @@ import {
|
||||
useLocale,
|
||||
type SupportedLocale,
|
||||
} from "../../src/presentation/i18n/index.ts";
|
||||
import {
|
||||
ErrorSummary,
|
||||
Form,
|
||||
FormField,
|
||||
useAppForm,
|
||||
} from "../../src/presentation/forms/index.ts";
|
||||
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
|
||||
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
|
||||
import { createTestApplication } from "../helpers/create-test-application.ts";
|
||||
|
||||
function LocaleHarness() {
|
||||
const { direction, locale, message, setLocale } = useLocale();
|
||||
@@ -50,7 +60,71 @@ function LocaleHarness() {
|
||||
);
|
||||
}
|
||||
|
||||
function LocaleSelect() {
|
||||
const { locale, message, setLocale } = useLocale();
|
||||
return (
|
||||
<>
|
||||
<label htmlFor="form-locale">{message("shell.locale")}</label>
|
||||
<select
|
||||
id="form-locale"
|
||||
onChange={(event) =>
|
||||
setLocale(event.currentTarget.value as SupportedLocale)
|
||||
}
|
||||
value={locale}
|
||||
>
|
||||
<option value="ko-KR">한국어</option>
|
||||
<option value="en-US">English</option>
|
||||
</select>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ValidatedForm() {
|
||||
const form = useAppForm({
|
||||
schema: z.object({ name: z.string().min(2) }).strict(),
|
||||
defaultValues: { name: "" },
|
||||
allowedServerFields: ["name"],
|
||||
mapToCommand: (values) => values,
|
||||
submit: async () => ({ ok: true as const, value: null }),
|
||||
});
|
||||
return (
|
||||
<Form onSubmit={(event) => void form.submitForm(event)}>
|
||||
<ErrorSummary
|
||||
fieldErrors={form.fieldErrors}
|
||||
formErrors={form.formErrors}
|
||||
fieldLabels={{ name: "Name" }}
|
||||
fieldId={form.fieldId}
|
||||
/>
|
||||
<FormField {...form.field("name")} label="Name" />
|
||||
<button type="submit">Submit</button>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
describe("locale provider runtime", () => {
|
||||
// 08-10. A shown error is kept as a message key, not a translated string.
|
||||
it("re-translates displayed form errors when the locale changes", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<LocaleProvider>
|
||||
<LocaleSelect />
|
||||
<ValidatedForm />
|
||||
</LocaleProvider>,
|
||||
);
|
||||
await user.click(screen.getByRole("button", { name: "Submit" }));
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||
"입력 내용을 확인해 주세요.Name: 입력값이 너무 짧습니다.",
|
||||
);
|
||||
|
||||
await user.selectOptions(screen.getByLabelText("언어"), "en-US");
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||
"Review the entered information.Name: This value is too short.",
|
||||
);
|
||||
expect(screen.getByRole("textbox", { name: "Name" })).toHaveAccessibleDescription(
|
||||
"This value is too short.",
|
||||
);
|
||||
});
|
||||
|
||||
it("switches copy and synchronizes the document language and direction", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
@@ -118,3 +192,44 @@ describe("locale provider runtime", () => {
|
||||
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("persisted locale preference", () => {
|
||||
it("stores the chosen locale and starts the next mount from it", async () => {
|
||||
const user = userEvent.setup();
|
||||
const stored = new Map<string, unknown>();
|
||||
const application = createTestApplication({
|
||||
preferences: {
|
||||
read: (name) => ({ ok: true as const, value: stored.get(name) }),
|
||||
write: (name, value) => {
|
||||
stored.set(name, value);
|
||||
return { ok: true as const };
|
||||
},
|
||||
remove: (name) => {
|
||||
stored.delete(name);
|
||||
return { ok: true as const };
|
||||
},
|
||||
},
|
||||
});
|
||||
const mount = () =>
|
||||
render(
|
||||
<ApplicationProvider application={application}>
|
||||
<PreferenceProviders>
|
||||
{/* Template sync (af3d8e6): upstream drives its app shell's
|
||||
language selector; this product's shells have none, so the
|
||||
harness selector stands in for it. */}
|
||||
<LocaleHarness />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>,
|
||||
);
|
||||
window.history.pushState({}, "", "/missing");
|
||||
|
||||
const first = mount();
|
||||
await user.selectOptions(await screen.findByLabelText("언어"), "en-US");
|
||||
expect(stored.get("LOCALE")).toBe("en-US");
|
||||
first.unmount();
|
||||
|
||||
mount();
|
||||
expect(await screen.findByLabelText("Language")).toHaveValue("en-US");
|
||||
expect(document.documentElement).toHaveAttribute("lang", "en-US");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { Pagination } from "../../src/presentation/design-system/index.ts";
|
||||
import { CollectionPage } from "../../src/presentation/templates/index.ts";
|
||||
|
||||
function pagination(page: number, pageCount: number) {
|
||||
return (
|
||||
<Pagination
|
||||
label="Pages"
|
||||
nextLabel="Next"
|
||||
onChange={() => {}}
|
||||
page={page}
|
||||
pageCount={pageCount}
|
||||
pageLabel={(candidate) => `Page ${candidate}`}
|
||||
previousLabel="Previous"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function pageLinks(): string[] {
|
||||
return screen
|
||||
.getAllByRole("link")
|
||||
.map((link) => link.textContent ?? "");
|
||||
}
|
||||
|
||||
describe("Pagination windowing", () => {
|
||||
it("links the first, last and neighbouring pages only", () => {
|
||||
render(pagination(50, 5000));
|
||||
|
||||
expect(pageLinks()).toEqual([
|
||||
"Page 1",
|
||||
"Page 49",
|
||||
"Page 50",
|
||||
"Page 51",
|
||||
"Page 5000",
|
||||
]);
|
||||
expect(screen.getByRole("link", { name: "Page 50" })).toHaveAttribute(
|
||||
"aria-current",
|
||||
"page",
|
||||
);
|
||||
});
|
||||
|
||||
it("links a single skipped page instead of eliding it", () => {
|
||||
render(pagination(3, 5000));
|
||||
expect(pageLinks()).toEqual([
|
||||
"Page 1",
|
||||
"Page 2",
|
||||
"Page 3",
|
||||
"Page 4",
|
||||
"Page 5000",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps every page of a short range", () => {
|
||||
render(pagination(1, 3));
|
||||
expect(pageLinks()).toEqual(["Page 1", "Page 2", "Page 3"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pagination landmarks", () => {
|
||||
it("is a navigation landmark on its own", () => {
|
||||
render(pagination(1, 2));
|
||||
expect(screen.getByRole("navigation", { name: "Pages" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("does not nest a navigation landmark inside the collection page slot", () => {
|
||||
render(
|
||||
<CollectionPage heading={{ title: "Collection" }} pagination={pagination(1, 2)}>
|
||||
Results
|
||||
</CollectionPage>,
|
||||
);
|
||||
|
||||
const slot = screen.getByRole("navigation", { name: "페이지 탐색" });
|
||||
expect(within(slot).queryAllByRole("navigation")).toHaveLength(0);
|
||||
expect(within(slot).getByRole("group", { name: "Pages" })).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
// 08-12. A modified click is the browser's (new tab/window), not a page change.
|
||||
describe("Pagination modified clicks", () => {
|
||||
function renderWith(onChange: (page: number) => void) {
|
||||
render(
|
||||
<Pagination
|
||||
label="Pages"
|
||||
nextLabel="Next"
|
||||
onChange={onChange}
|
||||
page={1}
|
||||
pageCount={3}
|
||||
pageLabel={(candidate) => `Page ${candidate}`}
|
||||
previousLabel="Previous"
|
||||
/>,
|
||||
);
|
||||
return screen.getByRole("link", { name: "Page 2" });
|
||||
}
|
||||
|
||||
it.each([
|
||||
["Ctrl", { ctrlKey: true }],
|
||||
["Cmd", { metaKey: true }],
|
||||
["Shift", { shiftKey: true }],
|
||||
["Alt", { altKey: true }],
|
||||
])("leaves a %s click to the browser", (_, modifier) => {
|
||||
const onChange = vi.fn();
|
||||
const link = renderWith(onChange);
|
||||
const notPrevented = fireEvent.click(link, { button: 0, ...modifier });
|
||||
expect(notPrevented).toBe(true);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("changes the page on a plain primary click", () => {
|
||||
const onChange = vi.fn();
|
||||
const link = renderWith(onChange);
|
||||
expect(fireEvent.click(link, { button: 0 })).toBe(false);
|
||||
expect(onChange).toHaveBeenCalledWith(2);
|
||||
});
|
||||
});
|
||||
@@ -4,10 +4,11 @@ import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
|
||||
import type { ApplicationOutputPorts } from "../../src/application/create-application.ts";
|
||||
import { createTechLogFeatureInstalledInput } from "../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
|
||||
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
|
||||
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../helpers/studio-install-context.ts";
|
||||
import { createTestApplication } from "../helpers/create-test-application.ts";
|
||||
import { createProductFeaturesStub } from "../helpers/runtime-capabilities-stub.ts";
|
||||
|
||||
/**
|
||||
* §3.5. The runtime kill switch, exercised through the running app.
|
||||
@@ -24,14 +25,17 @@ import { createProductFeaturesStub } from "../helpers/runtime-capabilities-stub.
|
||||
*
|
||||
* So the ownership map is the fixture. `ROUTE_FEATURE_OWNER` is empty in this
|
||||
* product because no installed feature contributes a route; one real registered
|
||||
* route is attributed to a real installed feature here, and everything else —
|
||||
* router, shell, components, codecs — is the product's own.
|
||||
* route is attributed to a feature here, and everything else — router, shell,
|
||||
* components, codecs — is the product's own.
|
||||
*
|
||||
* Template sync (af3d8e6). No feature is generator-installed here any more
|
||||
* (the sample carries NOT_INSTALLED), so the runtime's feature port is the
|
||||
* other half of the fixture: it reports the owner active or switched off.
|
||||
*/
|
||||
|
||||
const OWNED_ROUTE_ID = "TECH_LOG_EXPLORE";
|
||||
const OWNER_FEATURE_ID = "reference-feature";
|
||||
const OWNER_FEATURE_ID = "fixture-feature";
|
||||
const OWNED_ROUTE_PATH = "/explore";
|
||||
const OWNED_ROUTE_NAV_LABEL = "탐색";
|
||||
|
||||
vi.mock("../../src/features/installed-feature-contracts.ts", async (original) => {
|
||||
const actual = await original<
|
||||
@@ -51,6 +55,19 @@ const { ApplicationProvider } = await import(
|
||||
);
|
||||
const { renderWithQueryProviders } = await import("../helpers/query-providers.tsx");
|
||||
|
||||
function ownerFeaturePort(
|
||||
disabled: boolean,
|
||||
): ApplicationOutputPorts["productFeatures"] {
|
||||
const status = Object.freeze({
|
||||
featureId: OWNER_FEATURE_ID,
|
||||
state: disabled ? ("DISABLED_BY_CONFIG" as const) : ("ACTIVE" as const),
|
||||
});
|
||||
return Object.freeze({
|
||||
getSnapshot: () => Object.freeze([status]),
|
||||
isActive: (featureId: string) => featureId === OWNER_FEATURE_ID && !disabled,
|
||||
});
|
||||
}
|
||||
|
||||
function renderAt(path: string, disabled: boolean) {
|
||||
window.history.pushState({}, "", path);
|
||||
return render(
|
||||
@@ -59,16 +76,12 @@ function renderAt(path: string, disabled: boolean) {
|
||||
application={createTestApplication({
|
||||
session: createAnonymousSessionAdapter(),
|
||||
featureInputs: { "tech-log": createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input },
|
||||
...(disabled
|
||||
? {
|
||||
productFeatures: createProductFeaturesStub({
|
||||
[OWNER_FEATURE_ID]: "DISABLED_BY_CONFIG",
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
productFeatures: ownerFeaturePort(disabled),
|
||||
})}
|
||||
>
|
||||
<AppRouter />
|
||||
<PreferenceProviders>
|
||||
<AppRouter />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -10,6 +10,23 @@ import { deriveAsyncState } from "../../src/application/view-models/async-state.
|
||||
import { AsyncSurface } from "../../src/presentation/components/async-surface.tsx";
|
||||
import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx";
|
||||
import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx";
|
||||
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
|
||||
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
|
||||
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
|
||||
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
|
||||
import { createTestApplication } from "../helpers/create-test-application.ts";
|
||||
import { createTechLogFeatureInstalledInput } from "../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
|
||||
import { renderWithQueryProviders } from "../helpers/query-providers.tsx";
|
||||
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../helpers/studio-install-context.ts";
|
||||
|
||||
// The Explore page stands in for any route page with a programmer defect
|
||||
// (template sync af3d8e6: upstream uses its states example page, which this
|
||||
// product deleted).
|
||||
vi.mock("../../src/features/tech-log/presentation/public/pages/explore-page.tsx", () => ({
|
||||
ExplorePage: function BrokenPage(): never {
|
||||
throw new Error("ordinary render defect");
|
||||
},
|
||||
}));
|
||||
|
||||
function Defect(): ReactNode {
|
||||
throw new Error("raw render stack");
|
||||
@@ -35,9 +52,46 @@ describe("render recovery boundaries", () => {
|
||||
routeId: "APP_HOME",
|
||||
buildId: "build-a",
|
||||
boundaryName: "feature",
|
||||
incidentId: expect.stringMatching(/^[0-9a-f]{8}$/),
|
||||
});
|
||||
});
|
||||
|
||||
// 08-07. The route failure page shows the reference the user quotes, the
|
||||
// same id the render diagnostic records, and a way out besides the URL.
|
||||
it("shows a route render failure's support reference and records it", async () => {
|
||||
const record = vi.fn();
|
||||
window.history.pushState({}, "", "/explore");
|
||||
render(
|
||||
renderWithQueryProviders(
|
||||
<ApplicationProvider
|
||||
application={createTestApplication({
|
||||
diagnostics: { record },
|
||||
featureInputs: {
|
||||
"tech-log": createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input,
|
||||
},
|
||||
})}
|
||||
>
|
||||
<PreferenceProviders>
|
||||
<AppRouter buildId="build-a" />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/);
|
||||
const incidentId = reference.textContent?.split(":").at(-1);
|
||||
expect(record).toHaveBeenCalledWith({
|
||||
level: "error",
|
||||
eventId: "ui.render.failed",
|
||||
context: expect.objectContaining({
|
||||
route_id: "TECH_LOG_EXPLORE",
|
||||
build_id: "build-a",
|
||||
correlation_id: incidentId,
|
||||
}),
|
||||
});
|
||||
expect(screen.getByRole("button", { name: "한 번 새로고침" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("keeps normalized operational failures in normal async state", () => {
|
||||
const state = deriveAsyncState({
|
||||
failure: createFailure("SERVER_FAILURE", "LIST", 0),
|
||||
@@ -72,6 +126,39 @@ describe("render recovery boundaries", () => {
|
||||
expect(shell).not.toHaveTextContent("stack");
|
||||
});
|
||||
|
||||
it.each(["CONFIG_FETCH_FAILED", "CONFIG_TIMEOUT", "MANIFEST_FETCH_FAILED", "MANIFEST_TIMEOUT"])(
|
||||
"offers a retry for the network failure %s (09-10)",
|
||||
async (code) => {
|
||||
const onRetry = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<BootErrorShell
|
||||
kind="BOOT_CONFIG_FAILURE"
|
||||
code={code}
|
||||
supportReference={`build-a:${code}`}
|
||||
onRetry={onRetry}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||
"네트워크 연결을 확인한 뒤 다시 시도해 주세요.",
|
||||
);
|
||||
await user.click(screen.getByRole("button", { name: "다시 시도" }));
|
||||
expect(onRetry).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("offers no retry for a failure a reload cannot fix (09-10)", () => {
|
||||
render(
|
||||
<BootErrorShell
|
||||
kind="BOOT_CONFIG_FAILURE"
|
||||
code="CONFIG_SCHEMA_INVALID"
|
||||
supportReference="build-a:CONFIG_SCHEMA_INVALID"
|
||||
onRetry={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
});
|
||||
|
||||
it("allows a boundary reset action without reloading the page", async () => {
|
||||
let shouldThrow = true;
|
||||
function Recoverable() {
|
||||
@@ -123,4 +210,18 @@ describe("render recovery boundaries", () => {
|
||||
);
|
||||
expect(await screen.findByText("next route")).toBeVisible();
|
||||
});
|
||||
|
||||
it("renders the default fallback in the current locale", () => {
|
||||
render(
|
||||
<LocaleProvider initialLocale="en-US">
|
||||
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
|
||||
<Defect />
|
||||
</FeatureBoundary>
|
||||
</LocaleProvider>,
|
||||
);
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(
|
||||
"The page could not be displayed.",
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "Try again" })).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { act, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, expectTypeOf, it } from "vitest";
|
||||
import { describe, expect, expectTypeOf, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
createMemoryRouter,
|
||||
@@ -13,10 +13,12 @@ import {
|
||||
|
||||
import { createExternalAuthSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
|
||||
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
|
||||
import type { ApplicationOutputPorts } from "../../src/application/create-application.ts";
|
||||
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_FEATURE_ID } from "../../src/features/tech-log/application/tech-log-feature-input.ts";
|
||||
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
|
||||
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
|
||||
import { renderWithQueryProviders } from "../helpers/query-providers.tsx";
|
||||
import {
|
||||
AppRouter,
|
||||
@@ -118,25 +120,47 @@ function createSignedInSessionAdapter() {
|
||||
attachCredential: async () => ({ headers: {} }),
|
||||
recoverSession: async () => "restored" as const,
|
||||
notifyUnauthenticated: () => {},
|
||||
// Template sync (af3d8e6): the external owner must name its subject.
|
||||
readSubject: () => "router-test-subject",
|
||||
});
|
||||
}
|
||||
|
||||
function renderRouter(session = createAnonymousSessionAdapter()) {
|
||||
function renderRouter(
|
||||
session = createAnonymousSessionAdapter(),
|
||||
diagnostics: ApplicationOutputPorts["diagnostics"] = { record: () => {} },
|
||||
) {
|
||||
const techLog = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT);
|
||||
return render(
|
||||
renderWithQueryProviders(
|
||||
<ApplicationProvider
|
||||
application={createTestApplication({
|
||||
session,
|
||||
diagnostics,
|
||||
featureInputs: { [TECH_LOG_FEATURE_ID]: techLog.input },
|
||||
})}
|
||||
>
|
||||
<AppRouter />
|
||||
<PreferenceProviders>
|
||||
<AppRouter />
|
||||
</PreferenceProviders>
|
||||
</ApplicationProvider>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** A back/forward style navigation that leaves focus where the user left it. */
|
||||
function navigateByHistory(url: string) {
|
||||
act(() => {
|
||||
window.history.pushState({}, "", url);
|
||||
window.dispatchEvent(new PopStateEvent("popstate"));
|
||||
});
|
||||
}
|
||||
|
||||
function routeChangeReports(record: ReturnType<typeof vi.fn>) {
|
||||
return record.mock.calls.filter(
|
||||
([event]) => (event as { eventId: string }).eventId === "route.changed",
|
||||
).length;
|
||||
}
|
||||
|
||||
describe("generic application router", () => {
|
||||
it("renders and canonicalizes an isolated non-installed route codec contract", async () => {
|
||||
expect(ROUTE_REGISTRY).not.toHaveProperty("REVIEW_FIXTURE");
|
||||
@@ -434,4 +458,54 @@ describe("generic application router", () => {
|
||||
expect(screen.getByRole("navigation", { name: "Studio 주 탐색" })).toBeVisible();
|
||||
expect(window.location.pathname).toBe("/studio/missing");
|
||||
});
|
||||
|
||||
// Template sync (af3d8e6). The template pins these two router behaviours on
|
||||
// its example screens; this product deleted those, so they are pinned on
|
||||
// TechLog routes instead.
|
||||
it("ignores unknown query parameters on a route without search and keeps the URL", async () => {
|
||||
// D-16: `?utm_source=` or an OAuth callback parameter is not an invalid
|
||||
// address. The `none` codec drops it from the parsed input only.
|
||||
window.history.pushState({}, "", "/projects?utm_source=mail#top");
|
||||
const { container } = renderRouter();
|
||||
|
||||
expect(
|
||||
await screen.findByRole(
|
||||
"heading",
|
||||
{ name: "프로젝트", level: 1 },
|
||||
{ timeout: 5000 },
|
||||
),
|
||||
).toBeVisible();
|
||||
expect(container.querySelector('[data-surface="invalid-route"]')).toBeNull();
|
||||
expect(`${window.location.pathname}${window.location.search}`).toBe(
|
||||
"/projects?utm_source=mail",
|
||||
);
|
||||
});
|
||||
|
||||
it("runs the route lifecycle on the authentication-required surface", async () => {
|
||||
// Title and route telemetry belong to every answer a route gives, not only
|
||||
// to the page it renders once allowed.
|
||||
const record = vi.fn();
|
||||
window.history.pushState({}, "", "/");
|
||||
const { container } = renderRouter(createAnonymousSessionAdapter(), {
|
||||
record,
|
||||
});
|
||||
await screen.findByRole("heading", { name: "TechLog", level: 1 });
|
||||
|
||||
navigateByHistory("/studio");
|
||||
|
||||
await waitFor(
|
||||
() =>
|
||||
expect(
|
||||
container.querySelector('[data-surface="authentication-required"]'),
|
||||
).not.toBeNull(),
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
expect(routeChangeReports(record)).toBeGreaterThan(1);
|
||||
expect(record).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
eventId: "route.changed",
|
||||
context: expect.objectContaining({ route_id: "TECH_LOG_STUDIO_HOME" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.ts";
|
||||
@@ -22,7 +23,7 @@ const runtimeConfig = {
|
||||
|
||||
const releaseManifest = {
|
||||
schemaVersion: 1,
|
||||
appVersion: "0.1.0",
|
||||
appVersion: "0.2.0",
|
||||
buildId: "local-build",
|
||||
commitSha: "local",
|
||||
configSchemaVersion: "1",
|
||||
@@ -95,4 +96,63 @@ describe("production runtime application tree", () => {
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
expect(composition).not.toHaveProperty("ports");
|
||||
});
|
||||
|
||||
it("keeps locale state across a session scope fence and disposes routers", async () => {
|
||||
const user = userEvent.setup();
|
||||
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url =
|
||||
typeof input === "string"
|
||||
? input
|
||||
: input instanceof URL
|
||||
? input.href
|
||||
: input.url;
|
||||
return Response.json(
|
||||
url.includes("release-manifest") ? releaseManifest : runtimeConfig,
|
||||
);
|
||||
});
|
||||
window.localStorage.clear();
|
||||
const composition = await createRuntimeComposition({
|
||||
fetcher,
|
||||
host: { localStorage: window.localStorage },
|
||||
});
|
||||
// Spies call through; each router's history listens to popstate.
|
||||
const add = vi.spyOn(window, "addEventListener");
|
||||
const remove = vi.spyOn(window, "removeEventListener");
|
||||
const popstateCalls = (spy: typeof add | typeof remove) =>
|
||||
spy.mock.calls.filter(([type]) => type === "popstate").length;
|
||||
|
||||
try {
|
||||
// Template sync (af3d8e6). Upstream picks the language in its app
|
||||
// shell and signs in from the shell's session button. This product's
|
||||
// shells have no language selector, so the preference is stored first,
|
||||
// and the demo sign-in is the Studio sign-in gate's button.
|
||||
composition.application.preferences.setLocale("en-US");
|
||||
window.history.pushState({}, "", "/studio");
|
||||
const app = render(<RuntimeApplication composition={composition} />);
|
||||
const signIn = await screen.findByRole("button", {
|
||||
name: "Start sign-in",
|
||||
});
|
||||
expect(document.documentElement).toHaveAttribute("lang", "en-US");
|
||||
// Only the live provider holds the choice from here on; a remount would
|
||||
// start over from empty storage.
|
||||
window.localStorage.clear();
|
||||
|
||||
// Demo sign-in changes the session: the scope goes FENCED, then READY.
|
||||
await user.click(signIn);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
document.querySelector('[data-surface="authentication-required"]'),
|
||||
).toBeNull(),
|
||||
);
|
||||
expect(document.documentElement).toHaveAttribute("lang", "en-US");
|
||||
|
||||
app.unmount();
|
||||
expect(popstateCalls(add)).toBeGreaterThan(0);
|
||||
expect(popstateCalls(remove)).toBe(popstateCalls(add));
|
||||
} finally {
|
||||
add.mockRestore();
|
||||
remove.mockRestore();
|
||||
await composition.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.ts";
|
||||
|
||||
/**
|
||||
* 06-05. The optional host reports a Service Worker that did not start, but
|
||||
* only if the composition hands it the application's telemetry port. This
|
||||
* test runs the real composition with an ACTIVE selection and a first install
|
||||
* that fails, and records what reaches the telemetry adapter.
|
||||
*/
|
||||
|
||||
const emitted = vi.hoisted(
|
||||
() => [] as Array<readonly [string, Record<string, unknown>]>,
|
||||
);
|
||||
|
||||
vi.mock("../../src/features/installed-runtime-capabilities.ts", async (importOriginal) => {
|
||||
const original =
|
||||
await importOriginal<typeof import("../../src/features/installed-runtime-capabilities.ts")>();
|
||||
return {
|
||||
INSTALLED_RUNTIME_CAPABILITIES: Object.freeze({
|
||||
...original.INSTALLED_RUNTIME_CAPABILITIES,
|
||||
serviceWorker: Object.freeze({
|
||||
mode: "ACTIVE",
|
||||
scriptPath: "service-worker.js",
|
||||
handlers: Object.freeze(["PWA_STATIC_ASSETS"]),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../src/adapters/telemetry/index.ts", async (importOriginal) => {
|
||||
const original =
|
||||
await importOriginal<typeof import("../../src/adapters/telemetry/index.ts")>();
|
||||
return {
|
||||
...original,
|
||||
createTelemetryAdapter: (
|
||||
options: Parameters<typeof original.createTelemetryAdapter>[0],
|
||||
) => {
|
||||
const adapter = original.createTelemetryAdapter(options);
|
||||
return Object.freeze({
|
||||
...adapter,
|
||||
emit(eventName: string, attributes: Record<string, unknown>) {
|
||||
emitted.push([eventName, attributes]);
|
||||
adapter.emit(eventName as never, attributes);
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const origin = "http://localhost";
|
||||
|
||||
const runtimeConfig = {
|
||||
APP_ENV: "local",
|
||||
API_BASE_URL: "http://localhost:8080",
|
||||
REQUEST_TIMEOUT_MS: 10_000,
|
||||
MAX_RETRY_ATTEMPTS: 2,
|
||||
TELEMETRY_ENABLED: false,
|
||||
AUTH_MODE: "demo",
|
||||
CONFIG_SCHEMA_VERSION: "1",
|
||||
API_CONTRACT_VERSION: "1",
|
||||
RELEASE_MANIFEST_URL: "/release-manifest.json",
|
||||
BUILD_ID: "local-build",
|
||||
RELEASE_ID: "local-release",
|
||||
};
|
||||
|
||||
const releaseManifest = {
|
||||
schemaVersion: 1,
|
||||
appVersion: "0.2.0",
|
||||
buildId: "local-build",
|
||||
commitSha: "local",
|
||||
configSchemaVersion: "1",
|
||||
apiContractVersion: "1",
|
||||
assetManifestHash: "test-hash",
|
||||
releaseId: "local-release",
|
||||
builtAt: "2026-07-26T00:00:00.000Z",
|
||||
routeChunks: {
|
||||
"route-home": "assets/home.js",
|
||||
"route-examples-ui": "assets/ui.js",
|
||||
"route-examples-states": "assets/states.js",
|
||||
"route-examples-auth": "assets/auth.js",
|
||||
"route-not-found": "assets/not-found.js",
|
||||
},
|
||||
};
|
||||
|
||||
async function fetcher(input: RequestInfo | URL): Promise<Response> {
|
||||
const url =
|
||||
typeof input === "string"
|
||||
? input
|
||||
: input instanceof URL
|
||||
? input.href
|
||||
: input.url;
|
||||
return Response.json(
|
||||
url.includes("release-manifest") ? releaseManifest : runtimeConfig,
|
||||
);
|
||||
}
|
||||
|
||||
/** A first install whose worker turns `redundant` (install event rejected). */
|
||||
function failingInstallContainer(): ServiceWorkerContainer {
|
||||
const register = vi.fn(
|
||||
async (scriptURL: string | URL, options?: RegistrationOptions) => {
|
||||
const installing = {
|
||||
scriptURL: new URL(scriptURL, origin).href,
|
||||
state: "installing",
|
||||
addEventListener(type: string, listener: () => void) {
|
||||
if (type !== "statechange") return;
|
||||
queueMicrotask(() => {
|
||||
installing.state = "redundant";
|
||||
listener();
|
||||
});
|
||||
},
|
||||
removeEventListener() {},
|
||||
};
|
||||
return {
|
||||
scope: new URL(options?.scope ?? "/", origin).href,
|
||||
installing,
|
||||
waiting: null,
|
||||
active: null,
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
update: vi.fn(async () => {}),
|
||||
} as unknown as ServiceWorkerRegistration;
|
||||
},
|
||||
);
|
||||
return {
|
||||
controller: null,
|
||||
register,
|
||||
getRegistration: vi.fn(async () => undefined),
|
||||
getRegistrations: vi.fn(async () => []),
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
} as unknown as ServiceWorkerContainer;
|
||||
}
|
||||
|
||||
describe("06-05 runtime composition reports a Service Worker install failure", () => {
|
||||
afterEach(() => {
|
||||
emitted.length = 0;
|
||||
});
|
||||
|
||||
it("emits exactly one service-worker.start.failed through the application telemetry port", async () => {
|
||||
const container = failingInstallContainer();
|
||||
const composition = await createRuntimeComposition({
|
||||
fetcher,
|
||||
host: {
|
||||
location: { origin },
|
||||
navigator: { serviceWorker: container },
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await composition.optional.startAfterMount();
|
||||
|
||||
expect(container.register).toHaveBeenCalledTimes(1);
|
||||
expect(composition.optional.health().serviceWorker).toBe("DEGRADED");
|
||||
expect(
|
||||
emitted.filter(([eventName]) => eventName.startsWith("service-worker.")),
|
||||
).toEqual([
|
||||
[
|
||||
"service-worker.start.failed",
|
||||
{ error_kind: "INSTALL_FAILED", build_id: "local-build" },
|
||||
],
|
||||
]);
|
||||
} finally {
|
||||
await composition.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { Button, Tooltip } from "../../src/presentation/design-system/index.ts";
|
||||
|
||||
describe("Tooltip", () => {
|
||||
it("describes the focusable trigger itself", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<>
|
||||
<p id="existing-hint">Existing hint</p>
|
||||
<Tooltip content="Optional detail">
|
||||
<Button aria-describedby="existing-hint">Help</Button>
|
||||
</Tooltip>
|
||||
</>,
|
||||
);
|
||||
|
||||
await user.tab();
|
||||
const trigger = screen.getByRole("button", { name: "Help" });
|
||||
expect(trigger).toHaveFocus();
|
||||
expect(trigger).toHaveAccessibleDescription("Existing hint Optional detail");
|
||||
});
|
||||
|
||||
it("closes with Escape and opens again on the next focus", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<>
|
||||
<Tooltip content="Optional detail">
|
||||
<Button>Help</Button>
|
||||
</Tooltip>
|
||||
<Button>Elsewhere</Button>
|
||||
</>,
|
||||
);
|
||||
|
||||
await user.tab();
|
||||
const tooltip = screen.getByRole("tooltip");
|
||||
expect(tooltip).toBeVisible();
|
||||
|
||||
await user.keyboard("{Escape}");
|
||||
expect(tooltip).not.toBeVisible();
|
||||
expect(screen.getByRole("button", { name: "Help" })).toHaveFocus();
|
||||
|
||||
await user.tab();
|
||||
await user.tab({ shift: true });
|
||||
expect(screen.getByRole("tooltip")).toBeVisible();
|
||||
});
|
||||
|
||||
it("closes a hovered tooltip with Escape", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<Tooltip content="Optional detail">
|
||||
<Button>Help</Button>
|
||||
</Tooltip>,
|
||||
);
|
||||
|
||||
await user.hover(screen.getByRole("button", { name: "Help" }));
|
||||
await user.keyboard("{Escape}");
|
||||
expect(screen.getByRole("tooltip", { hidden: true })).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user