문제 tests/e2e/accessibility.spec.ts는 보호 라우트의 모든 API에 맨 배열 `[]`를 답했다. create:feature가 만드는 기능은 responseEnvelope: "ENVELOPE_V1"이라 `[]`는 ENVELOPE_MISMATCH가 되고, 페이지는 경고 상자를 그린다. spec은 h1과 axe만 봐서 오류 화면을 검사하고도 통과했고, 증거는 그 라우트를 "passed"로 적었다. 경로 파라미터는 `:resourceId`만 바꿔서 다른 이름을 쓰는 기능은 이 템플릿 파일을 고쳐야 했다. 고른 방법 (결정 D4 (b)) - tests/e2e/support/installed-api-answers.ts가 요청을 설치된 GET descriptor에서 method와 pathTemplate으로 찾는다. 출력 스키마가 빈 목록을 받으면 그 operation의 모양으로 답한다(Envelope면 MSW 시나리오와 같은 successEnvelope, 아니면 맨 배열). - 목록만 읽은 라우트는 로딩이 끝난 뒤 경고 상자(role="alert")가 없다고 단언한다. 모양이 다시 어긋나면 axe 통과 대신 여기서 실패한다. - 경로 파라미터는 이름과 상관없이 모두 a11y-1로 바꾼다. 기능을 더해도 spec을 고치지 않는다(16-03 앞 절반). - 설치된 GET이 아닌 요청, 빈 목록을 받지 않는 파라미터 없는 GET은 501로 답하고 그 목록이 비어 있다고 단언한다. - 매뉴얼 01·03, starter-experience, create-feature 참조, 수동 점검 문서의 "모든 API에 []", ".replace를 잇는다" 문장을 동작에 맞췄다. - 버린 대안: 전역 Envelope 응답(참조 기능 DTO가 거꾸로 깨짐), 기능마다 접근성 spec 생성(파일·실행 시간 증가). 위험·한계 - 한 자원을 읽는 GET(상세 페이지)에는 빈 목록 말고 줄 본문이 없다. 그 라우트는 지금처럼 실패 상태로 검사하고 a11y-data-state annotation만 남긴다. 경고 상자 단언은 그 라우트에서 건너뛴다. - write-a11y-report.ts의 증거는 annotation을 읽지 않는다. 상세 라우트도 "passed"로 적힌다. 검증 - 새 unit 테스트 6건: helper가 없을 때 실패, 추가 뒤 통과. - 템플릿 상태 chromium test:a11y 대상 spec 14건 통과. - create:feature sample-feature 상태에서 `@a11y /sample` 세 엔진 통과. 변이 1(Envelope 대신 맨 배열): 세 엔진 모두 경고 상자 단언으로 실패. 변이 2(빈·성공 상태에서만 보이는 이름 없는 버튼): 세 엔진 모두 axe button-name으로 실패. 생성 파일은 지웠다. - check:types:test, eslint, verify:documentation, check:ci 통과. Refs: docs/reviews/2026-11-03-maturity-review/11-tests-browser-release-scale.md 11-01 Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-03
197 lines
6.0 KiB
TypeScript
197 lines
6.0 KiB
TypeScript
import { delay, http, HttpResponse, type JsonBodyType } from "msw";
|
|
|
|
import {
|
|
httpScenarioOperationFacts,
|
|
type HttpScenarioContract,
|
|
type HttpScenarioId,
|
|
type HttpScenarioOperationId,
|
|
} from "../scenarios/catalog.ts";
|
|
|
|
/**
|
|
* 16-02. One MSW handler that answers an installed HTTP operation with one
|
|
* catalog scenario. The route, the success status and the response ceiling
|
|
* come from the operation's own descriptor, so a feature test passes its
|
|
* contract and needs no catalog entry. An operation that declares
|
|
* `responseEnvelope: "ENVELOPE_V1"` is answered the way the paired backend
|
|
* answers (clean-architecture-backend-template docs/web/http-contract.md §1):
|
|
* every JSON body is an Envelope and a null field is dropped with its key.
|
|
*
|
|
* server.use(createHttpScenarioHandler(LIST_X_CONTRACT, {
|
|
* scenario: "server-terminal-503", payload: [...],
|
|
* }));
|
|
*/
|
|
export type HttpScenarioHandlerOptions = Readonly<{
|
|
baseUrl?: string;
|
|
scenario?: HttpScenarioId;
|
|
/** The success body; `empty` answers `[]` instead. */
|
|
payload: JsonBodyType;
|
|
onAttempt?(attempt: Readonly<{
|
|
operationId: HttpScenarioOperationId;
|
|
scenarioId: HttpScenarioId;
|
|
attempt: number;
|
|
}>): void;
|
|
}>;
|
|
|
|
export function createHttpScenarioHandler(
|
|
installed: HttpScenarioContract,
|
|
options: HttpScenarioHandlerOptions,
|
|
) {
|
|
const { operationId, method, pathTemplate } = installed.contract;
|
|
const scenarioId = options.scenario ?? "success";
|
|
const facts = httpScenarioOperationFacts(installed);
|
|
// MSW path params are `:name`; descriptors write `{name}`.
|
|
const url = `${options.baseUrl ?? "https://api.test"}${pathTemplate.replace(
|
|
/\{([^}]+)\}/gu,
|
|
":$1",
|
|
)}`;
|
|
let attempt = 0;
|
|
return http[method.toLowerCase() as Lowercase<typeof method>](url, () => {
|
|
attempt += 1;
|
|
options.onAttempt?.({ operationId, scenarioId, attempt });
|
|
return scenarioResponse(
|
|
scenarioId,
|
|
scenarioId === "empty" ? [] : options.payload,
|
|
attempt,
|
|
facts,
|
|
);
|
|
});
|
|
}
|
|
|
|
async function scenarioResponse(
|
|
scenario: HttpScenarioId,
|
|
payload: JsonBodyType,
|
|
attempt: number,
|
|
{
|
|
ceiling,
|
|
successStatus,
|
|
enveloped,
|
|
}: ReturnType<typeof httpScenarioOperationFacts>,
|
|
) {
|
|
const body = (data: JsonBodyType) => (enveloped ? successEnvelope(data) : data);
|
|
const problem = (status: number, code: string) =>
|
|
enveloped ? failureEnvelope(status, code) : problemDetails(status, code);
|
|
if (scenario === "slow") await delay(50);
|
|
if (scenario === "timeout" || scenario === "aborted") {
|
|
await delay("infinite");
|
|
}
|
|
if (scenario === "network-error") return HttpResponse.error();
|
|
if (scenario === "content-type-mismatch") {
|
|
return new HttpResponse("<html>not json</html>", {
|
|
status: successStatus,
|
|
headers: { "Content-Type": "text/html" },
|
|
});
|
|
}
|
|
if (scenario === "malformed-json") {
|
|
return new HttpResponse("{invalid", {
|
|
status: successStatus,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
if (scenario === "envelope-mismatch") {
|
|
// The frame the operation does not read: a bare DTO for an Envelope one.
|
|
return HttpResponse.json(enveloped ? payload : { data: payload }, {
|
|
status: successStatus,
|
|
});
|
|
}
|
|
if (scenario === "schema-mismatch") {
|
|
return HttpResponse.json(body({ unexpected: true }), {
|
|
status: successStatus,
|
|
});
|
|
}
|
|
if (scenario === "unauthenticated-401") {
|
|
return HttpResponse.json(problem(401, "AUTH_REQUIRED"), { status: 401 });
|
|
}
|
|
if (scenario === "forbidden-403") {
|
|
return HttpResponse.json(problem(403, "FORBIDDEN"), { status: 403 });
|
|
}
|
|
if (scenario === "not-found-404") {
|
|
return HttpResponse.json(problem(404, "NOT_FOUND"), { status: 404 });
|
|
}
|
|
if (scenario === "conflict-409") {
|
|
return HttpResponse.json(problem(409, "CONFLICT"), { status: 409 });
|
|
}
|
|
if (scenario === "in-flight-409") {
|
|
return HttpResponse.json(problem(409, "IDEMPOTENT_IN_FLIGHT"), {
|
|
status: 409,
|
|
});
|
|
}
|
|
if (scenario === "validation-422") {
|
|
return HttpResponse.json(problem(422, "VALIDATION_REJECTED"), {
|
|
status: 422,
|
|
});
|
|
}
|
|
if (scenario === "rate-limited-429") {
|
|
return HttpResponse.json(problem(429, "RATE_LIMITED"), {
|
|
status: 429,
|
|
headers: { "Retry-After": "1" },
|
|
});
|
|
}
|
|
if (
|
|
scenario === "server-terminal-503" ||
|
|
(scenario === "server-retry-success" && attempt === 1)
|
|
) {
|
|
return HttpResponse.json(problem(503, "SERVER_FAILURE"), { status: 503 });
|
|
}
|
|
if (scenario === "response-too-large") {
|
|
const bytes = new Uint8Array(ceiling + 1).fill(0x20);
|
|
bytes[0] = 0x5b;
|
|
bytes[bytes.length - 1] = 0x5d;
|
|
return new HttpResponse(
|
|
new ReadableStream<Uint8Array>({
|
|
start(controller) {
|
|
controller.enqueue(bytes);
|
|
controller.close();
|
|
},
|
|
}),
|
|
{
|
|
status: successStatus,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Content-Length": String(bytes.byteLength),
|
|
},
|
|
},
|
|
);
|
|
}
|
|
return HttpResponse.json(body(payload), { status: successStatus });
|
|
}
|
|
|
|
function problemDetails(status: number, code: string) {
|
|
return Object.freeze({
|
|
type: `https://api.test/problems/${code.toLowerCase()}`,
|
|
title: code,
|
|
status,
|
|
code,
|
|
});
|
|
}
|
|
|
|
const ENVELOPE_META = Object.freeze({
|
|
requestId: "scenario-request",
|
|
traceId: "0af7651916cd43dd8448eb211c80319c",
|
|
});
|
|
|
|
/** Also the accessibility e2e's answer (`tests/e2e/support/installed-api-answers.ts`). */
|
|
export function successEnvelope(data: JsonBodyType) {
|
|
return Object.freeze({
|
|
success: true,
|
|
...(data === null ? {} : { data }),
|
|
meta: ENVELOPE_META,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Every key the backend always sends. The frontend reads only `code` and
|
|
* `details`; `category`, `message` and `retryable` are never branched on.
|
|
*/
|
|
function failureEnvelope(status: number, code: string) {
|
|
return Object.freeze({
|
|
success: false,
|
|
error: Object.freeze({
|
|
code,
|
|
category: "SCENARIO",
|
|
message: "scenario message",
|
|
retryable: status >= 500 || code === "IDEMPOTENT_IN_FLIGHT",
|
|
}),
|
|
meta: ENVELOPE_META,
|
|
});
|
|
}
|