Files
tech-log-frontend/tests/component/application-mutation-optimistic-cache.test.tsx
T
DongHyeonkaandClaude Opus 5 afde2b1da1 chore: sync the frontend template from 5434760 to ebea300
Carries 21 template commits: the shared IndexedDB connection/transaction
kernel and the four runtimes moved onto it, the adapter barrel boundary and
the architecture rule that enforces it, the feature adapter contribution
model, `feature-http-binding`, the split of several oversized test files,
and the release identity now derived from the package name.

Product identity is unchanged. The three hard-coded `tech-log-frontend/…`
verifier ids are gone because the template derives them from the package
name and this package is `tech-log-frontend`.

Two decisions worth naming. The platform HTTP executor is the template's
verbatim — it now takes the installed contract so a feature's types flow
through the binding — and TechLog's four gateways, which address operations
by id, reach it through one adapter at the composition root instead of being
rewritten here. And the three derived CI baselines were recomputed from the
merged `config/ci/gates.json` rather than taken from either side: 94 command
definitions, 106 references, 141 artifacts, gate shape `629e5898…`. The
method was checked by first reproducing the pre-merge values from the
pre-merge file.

Verified here: types, lint, architecture, adapter inventory, CI contract,
design system, diagnostics, remediation ledger, browser security and build
all pass; 1789 unit, 152 component, 415 TechLog, 102 integration, 19
reference-feature, 17 recipe and 7 contract tests pass. Five gates stay
red and every one was reproduced at b297d65 first: `check:i18n`,
`check:registries`, `test:runtime-schema`, `verify:documentation` and
`test:sample-removal`.

Full decision record, including what was deliberately not carried and the
five open follow-ups, in `docs/operations/template-sync-2026-09-21.md`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 16:31:05 +09:00

214 lines
6.7 KiB
TypeScript

// @vitest-environment jsdom
import { act, renderHook } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
type ApplicationResult,
useApplicationMutation,
} from "../../src/presentation/adapters/query/application-query.ts";
import { createFailure } from "../../src/contracts/errors.ts";
import {
RESOURCE_INVALIDATION_TOPIC,
queryClient,
wrapper,
} from "./application-query-fixture.tsx";
describe("application mutation optimistic cache lifecycle", () => {
it("cancels an in-flight query before taking the optimistic snapshot", async () => {
const client = queryClient();
const key = ["resource", "ordered-update"];
client.setQueryData(key, ["existing"]);
let finishCancellation: () => void = () => {};
const cancellation = new Promise<void>((resolve) => {
finishCancellation = resolve;
});
const cancelQueries = vi
.spyOn(client, "cancelQueries")
.mockImplementation(async () => cancellation);
const getQueryData = vi.spyOn(client, "getQueryData");
const update = vi.fn((previous, input) => [
...(previous as string[]),
input,
]);
const execute = vi.fn(async () => ({
ok: true as const,
value: "created",
}));
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
execute,
currentData: ["existing"],
optimistic: { queryKey: key, update },
}),
{ wrapper: wrapper(client) },
);
let pending: Promise<ApplicationResult<string>> | undefined;
act(() => {
pending = hook.result.current.submit("created");
});
expect(cancelQueries).toHaveBeenCalledWith({
queryKey: key,
exact: true,
});
expect(getQueryData).not.toHaveBeenCalled();
expect(update).not.toHaveBeenCalled();
expect(execute).not.toHaveBeenCalled();
finishCancellation();
if (!pending) throw new Error("expected pending mutation");
await act(() => pending);
expect(getQueryData).toHaveBeenCalledWith(key);
expect(update).toHaveBeenCalledWith(["existing"], "created");
expect(execute).toHaveBeenCalledOnce();
expect(client.getQueryData(key)).toEqual(["existing", "created"]);
});
it("keeps a committed optimistic update when invalidation fails", async () => {
const client = queryClient();
const key = ["resource", "committed-update"];
client.setQueryData(key, ["existing"]);
vi.spyOn(client, "invalidateQueries").mockRejectedValue(
new Error("cache refresh failed"),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
execute: async () => ({ ok: true, value: "created" }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: ["existing"],
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(outcome).toEqual({ ok: true, value: "created" });
expect(client.getQueryData(key)).toEqual(["existing", "created"]);
});
it("normalizes an optimistic preparation defect without running the command", async () => {
const client = queryClient();
const key = ["resource", "invalid-optimistic-update"];
client.setQueryData(key, ["existing"]);
const execute = vi.fn(async () => ({
ok: true as const,
value: "created",
}));
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
execute,
currentData: ["existing"],
optimistic: {
queryKey: key,
update: () => {
throw new Error("private optimistic detail");
},
},
}),
{ wrapper: wrapper(client) },
);
let outcome;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(outcome).toMatchObject({
ok: false,
error: {
kind: "UNKNOWN_FAILURE",
effect: "NOT_STARTED",
operationId: "APPLICATION_MUTATION",
userMessageKey: "error.unknown_failure",
},
});
expect(JSON.stringify(outcome)).not.toContain("private optimistic detail");
expect(execute).not.toHaveBeenCalled();
expect(client.getQueryData(key)).toEqual(["existing"]);
});
it("removes an optimistic cache entry when no prior data existed", async () => {
const client = queryClient();
const key = ["resource", "new-optimistic-entry"];
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "NOT_APPLIED",
});
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
execute: async () => ({ ok: false, error: failure }),
currentData: true,
optimistic: {
queryKey: key,
update: (_previous, input) => [input],
},
}),
{ wrapper: wrapper(client) },
);
let outcome;
await act(async () => {
outcome = await hook.result.current.submit("temporary");
});
expect(outcome).toEqual({ ok: false, error: failure });
expect(client.getQueryData(key)).toBeUndefined();
expect(client.getQueryState(key)).toBeUndefined();
});
it("rolls optimistic data back and exposes a resolvable conflict", async () => {
const client = queryClient();
const key = ["resource", "list"];
client.setQueryData(key, ["existing"]);
const conflict = createFailure("CONFLICT", "CREATE", 0, {
effect: "NOT_APPLIED",
});
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
execute: async () => ({ ok: false, error: conflict }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome;
await act(async () => {
outcome = await hook.result.current.submit("conflicting");
});
expect(outcome).toEqual({ ok: false, error: conflict });
expect(client.getQueryData(key)).toEqual(["existing"]);
expect(hook.result.current.state.indicator).toBe("mutation-conflict");
expect(hook.result.current.state.overlay).toMatchObject({
mutationPending: false,
mutationConflict: true,
});
await act(() => hook.result.current.resolveConflict());
expect(hook.result.current.state.indicator).toBeNull();
expect(client.getQueryState(key)?.isInvalidated).toBe(true);
});});