Files
clean-architecture-frontend…/tests/component/application-query-bridge.test.tsx
T
DongHyeonkaandClaude Opus 5.5 5848493580 fix(presentation): show a disabled query as idle instead of empty (R3-4)
A disabled query (no data, no error, not fetching) fell through
deriveAsyncState to "empty", so AsyncSurface rendered the
"no items" copy before the query had even started.

- AsyncState.base gains "idle" for "not started / waiting on a
  precondition". A completed empty result (`[]`, `""`, `null`) stays
  "empty"; a real first load stays "initial-loading".
- AsyncSurface renders an optional `idle` slot for idle, else nothing
  (no skeleton, no aria-busy, no empty copy, no children).

Consumer-facing: AsyncState["base"] union adds "idle" (additive);
AsyncSurface gains an optional `idle` prop. No in-repo exhaustive
switch over base needed changes.

RED (before the fix, node scripts/run-vitest.ts on the two files):
  application-query-bridge > disabled query: expected 'empty' to be 'idle'
  async-surface > derives base state 4 ({}): expected 'empty' to be 'idle'
  async-surface > idle renders neither loading nor empty:
    toBeEmptyDOMElement() received the empty-copy section
  Tests 3 failed | 25 passed (pins for first load, [] and null empty passed)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:14:11 +09:00

255 lines
8.1 KiB
TypeScript

// @vitest-environment jsdom
import { onlineManager } from "@tanstack/react-query";
import { act, renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
type ApplicationResult,
useApplicationQuery,
} from "../../src/presentation/adapters/query/application-query.ts";
import { createFailure } from "../../src/contracts/errors.ts";
import { queryClient, wrapper } from "./application-query-fixture.tsx";
describe("application query inbound bridge", () => {
it("latches a background failure over stale data and clears it on retry success", async () => {
const client = queryClient();
const responses: ApplicationResult<string[]>[] = [
{ ok: true, value: ["first"] },
{
ok: false,
error: createFailure("SERVER_FAILURE", "LIST", 0),
},
{ ok: true, value: ["recovered"] },
];
const execute = vi.fn(async () => responses.shift() ?? responses[0]);
const hook = renderHook(
() =>
useApplicationQuery({
queryKey: ["resource", "list"],
execute,
}),
{ wrapper: wrapper(client) },
);
await waitFor(() => expect(hook.result.current.data).toEqual(["first"]));
await act(() => hook.result.current.retry());
await waitFor(() =>
expect(hook.result.current.state.indicator).toBe("stale-degraded"),
);
expect(hook.result.current.state.base).toBe("success");
expect(hook.result.current.data).toEqual(["first"]);
await act(() => hook.result.current.retry());
await waitFor(() =>
expect(hook.result.current.data).toEqual(["recovered"]),
);
expect(hook.result.current.state.indicator).toBeNull();
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);
const hook = renderHook(
() =>
useApplicationQuery({
queryKey: ["forbidden"],
execute: async () => ({ ok: false, error: failure }),
}),
{ wrapper: wrapper(client) },
);
await waitFor(() =>
expect(hook.result.current.state.base).toBe("terminal-error"),
);
expect(hook.result.current.state.failure).toBe(failure);
});
it("normalizes an unexpected execute rejection into a safe terminal failure", async () => {
const client = queryClient();
const hook = renderHook(
() =>
useApplicationQuery({
queryKey: ["unexpected-rejection"],
execute: async () => {
throw new Error("private upstream detail");
},
}),
{ wrapper: wrapper(client) },
);
await waitFor(() =>
expect(hook.result.current.state.base).toBe("terminal-error"),
);
expect(hook.result.current.state.failure).toMatchObject({
kind: "UNKNOWN_FAILURE",
operationId: "APPLICATION_QUERY",
userMessageKey: "error.unknown_failure",
action: "contact-support",
});
expect(JSON.stringify(hook.result.current.state.failure)).not.toContain(
"private upstream detail",
);
});
it("passes cancellation to the application and does not retain an unmounted error", async () => {
const client = queryClient();
let aborted = false;
const execute = vi.fn(
({ signal }: { signal: AbortSignal }) =>
new Promise<ApplicationResult<unknown>>((resolve) => {
signal.addEventListener(
"abort",
() => {
aborted = true;
resolve({
ok: false,
error: createFailure("REQUEST_ABORTED", "LIST", 0),
});
},
{ once: true },
);
}),
);
const hook = renderHook(
() =>
useApplicationQuery({
queryKey: ["cancelled"],
execute,
}),
{ wrapper: wrapper(client) },
);
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
hook.unmount();
await waitFor(() => expect(aborted).toBe(true));
expect(client.getQueryState(["cancelled"])?.status).not.toBe("error");
});
});