useApplicationQuery passed TanStack's isPending as isInitialLoading. A disabled query without data is pending (fetchStatus "idle"), so dependent queries waiting on a prerequisite showed a skeleton and aria-busy forever. Two changes were needed: - application-query.ts passes isPending && fetchStatus !== "idle". The review suggested isLoading, but with the default networkMode "online" an offline first load is "paused" (isFetching false), and isLoading would stop showing it as loading. - deriveAsyncState fell back to "initial-loading" whenever there was no data, no failure and no load, so the signal fix alone still produced initial-loading (checked). The fallback is now "empty". This also stops a query that resolves to null from looking like it loads forever. Verified: RED "does not report a disabled query without data as loading" failed with base "initial-loading" before and passes after; "still reports a real first load as loading, including a paused offline one" guards the other direction. check:architecture, check:types:app, check:types:test, lint, test:component pass; test:unit passes except the pre-existing removal-fixture test (needs generated artifacts/ files absent from a fresh worktree). test:reference-feature also passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
241 lines
7.6 KiB
TypeScript
241 lines
7.6 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).not.toBe("initial-loading");
|
|
expect(execute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
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");
|
|
});
|
|
});
|
|
|