test(setup): Testing Library 대기 기한을 전역 한 곳에서 정한다 (0929/10-01)

문제
lazy route 화면을 findBy*·waitFor 기본값(1초)으로 기다리는 테스트가 1코어
부하에서 코드와 무관하게 떨어진다. 수정 전 재현에서
runtime-application.test.tsx:65 "Unable to find role=heading name=Clean
Architecture Frontend"와 reference-production-vertical.test.tsx:103
"Unable to find role=button name=로그인 시작"이 났다. 두 DOM 모두
route-loading(aria-busy) 상태였다. 지난 리뷰는 router.test.tsx:244-250도
같은 이유로 실패했다고 적었다. React 19는 Suspense를 풀 때마다 실제 300ms
타이머(FALLBACK_THROTTLE_MS)를 기다린다. context route 표와 lazy 페이지를
거치는 화면은 렌더링 전에 1초 중 600ms를 쓴다. 이 사정을 아는 파일만
호출마다 { timeout: 5000 }을 붙이거나(7개 파일 13곳) 파일 단위로
configure를 바꿨다(reference-page). 새 테스트 작성자는 이 규칙을 알 방법이
없다.

고른 방법
tests/setup.ts에서 configure({ asyncUtilTimeout: 5_000 })를 한 번 정하고,
같은 값을 반복하던 호출·파일 단위 override를 지웠다. findBy*·waitFor는
DOM 변화가 오면 바로 끝나므로 기한은 멈춤을 알리는 용도뿐이다. 10초 테스트
제한의 절반이라 진짜 멈춤은 여전히 Testing Library의 DOM 덤프와 함께
실패한다. 기한을 늘리는 방식이라 고른 이유를 setup에 주석으로 남겼다.

버린 대안
- 가짜 시계: Testing Library는 Jest의 가짜 타이머만 알아본다
  (jestFakeTimersAreEnabled가 jest 전역을 본다). Vitest 가짜 타이머에서
  waitFor는 자기 타이머가 멈춰 끝나지 않는다. MSW와 user-event도 실제
  시계로 돈다.
- route chunk를 테스트에서 미리 import하기: chunk를 받아도 React의 300ms
  reveal 타이머와 렌더링 비용은 그대로 기한 안에 남는다. 테스트가 route
  모듈 목록을 따로 알아야 한다.
- 실패한 파일에만 timeout 붙이기: 지금 상태와 같다. 다음 lazy 화면
  테스트에서 같은 실패가 반복된다.

위험·한계
- 기다리다 실패하는 테스트는 실패까지 1초가 아니라 5초 걸린다. 부재를
  findBy·waitFor의 실패로 확인하는 테스트는 없다(grep으로 확인).
- 가짜 타이머를 쓰는 테스트의 waitFor는 이 값과 무관하다(가짜 시간).

검증
- RED(수정 전, taskset -c 0 + 같은 코어의 바쁜 이웃 1개, --maxWorkers=4,
  component·features·integration·platform/cardinality): 3회 중 1회 위 두
  테스트 실패.
- GREEN(같은 조건): 대상 6개 파일 6회, 넓은 묶음 5회 모두 통과. 바쁜
  이웃 2개로 3회 돌렸을 때도 이 커밋이 다루는 테스트는 모두 통과했다.
  넓은 묶음 한 번의 시간은 RED 91~111s(실패가 몰린 209s 회차 제외)
  -> GREEN 86~88s다.
- 기본 코어: tests/unit·component·integration 212파일 2,734개, features·
  platform·architecture·contract·runtime-schema 60파일 403개 통과.
  tsc -p tsconfig.test.json, 바꾼 파일 eslint 통과.

Refs: docs/reviews/2026-09-29-maturity-review/10-tests-fast-layers.md
This commit is contained in:
DongHyeonka
2026-11-01 21:23:10 +09:00
parent 582630062b
commit c03bf020c9
9 changed files with 16 additions and 39 deletions
-1
View File
@@ -90,7 +90,6 @@ describe("app shell mobile navigation drawer", () => {
const heading = await screen.findByRole(
"heading",
{ name: "UI 구성요소", level: 1 },
{ timeout: 5000 },
);
await waitFor(() => expect(heading).toHaveFocus());
expect(menuButton).toHaveAttribute("aria-expanded", "false");
+1 -1
View File
@@ -18,7 +18,7 @@ describe("boot entry (09-03)", () => {
await import("../../src/bootstrap/main.tsx");
const shell = await screen.findByRole("alert", undefined, { timeout: 5_000 });
const shell = await screen.findByRole("alert");
expect(shell).toHaveTextContent("애플리케이션을 시작할 수 없습니다.");
expect(document.querySelector("[data-boot-shell]")).toBeNull();
});
@@ -26,7 +26,7 @@ describe("unexpected boot failure (09-04)", () => {
await import("../../src/bootstrap/main.tsx");
const shell = await screen.findByRole("alert", undefined, { timeout: 5_000 });
const shell = await screen.findByRole("alert");
expect(shell).toHaveTextContent("BOOT_UNEXPECTED_FAILURE");
expect(shell).not.toHaveTextContent("BOOT_CONFIG_FAILURE");
expect(shell).toHaveTextContent("local-build");
@@ -195,7 +195,6 @@ describe("chunk recovery boundary classification", () => {
await screen.findByRole(
"heading",
{ name: "UI 구성요소", level: 1 },
{ timeout: 5000 },
),
).toBeVisible();
expect(
@@ -68,8 +68,6 @@ describe("runtime product feature switch", () => {
const surface = await screen.findByText(
(_, element) =>
element?.getAttribute("data-disabled-feature") === FEATURE_ID,
{},
{ timeout: 5000 },
);
expect(surface).toBeTruthy();
});
@@ -64,7 +64,6 @@ describe("route-level status surfaces", () => {
await screen.findByRole(
"heading",
{ name: "Clean Architecture Frontend", level: 1 },
{ timeout: 5000 },
),
).toBeVisible();
});
@@ -80,7 +79,6 @@ describe("route-level status surfaces", () => {
const heading = await screen.findByRole(
"heading",
{ name: "세션이 필요합니다.", level: 1 },
{ timeout: 5000 },
);
const surface = container.querySelector(
'[data-surface="authentication-required"]',
@@ -131,7 +129,6 @@ describe("route-level status surfaces", () => {
await screen.findByRole(
"button",
{ name: "로그인 시작" },
{ timeout: 5000 },
),
);
expect(beginSignIn).toHaveBeenCalledWith("/examples/auth#session");
@@ -143,7 +140,6 @@ describe("route-level status surfaces", () => {
const heading = await screen.findByRole(
"heading",
{ name: "페이지를 찾을 수 없습니다.", level: 1 },
{ timeout: 5000 },
);
const page = heading.closest("section");
expect(page).not.toBeNull();
+1 -10
View File
@@ -62,15 +62,8 @@ describe("generic application router", () => {
window.history.pushState({}, "", "/");
renderRouter();
// The starter action lives inside the lazily loaded home chunk, so this is
// the first wait in the file that has to outlast a chunk load rather than
// an already-mounted shell element.
await user.click(
await screen.findByRole(
"link",
{ name: "플랫폼 구성 보기" },
{ timeout: 5000 },
),
await screen.findByRole("link", { name: "플랫폼 구성 보기" }),
);
await waitFor(() =>
@@ -195,7 +188,6 @@ describe("generic application router", () => {
expect(
container.querySelector(`[data-surface="${surface}"]`),
).not.toBeNull(),
{ timeout: 5000 },
);
await waitFor(() => expect(document.title).toBe(title));
expect(
@@ -220,7 +212,6 @@ describe("generic application router", () => {
await screen.findByRole(
"heading",
{ name: "UI 구성요소", level: 1 },
{ timeout: 5000 },
),
).toBeVisible();
expect(container.querySelector('[data-surface="invalid-route"]')).toBeNull();
@@ -4,15 +4,9 @@ import {
QueryClient,
QueryClientProvider,
} from "@tanstack/react-query";
import {
configure,
getConfig,
render,
screen,
waitFor,
} from "@testing-library/react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { createDemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
import type { AuthSessionPort } from "../../../src/application/ports/auth-session-port.ts";
@@ -128,16 +122,6 @@ function inputWith(
}
describe("reference feature page states", () => {
// Entering an installed route resolves the context route table and then a
// lazy page, and React holds each Suspense reveal for up to 300ms. That
// floor alone uses half of Testing Library's 1s findBy default, so a busy
// host misses it and reports a missing heading instead of a slow route.
// Keep the wider wait scoped to this file; the test timeout still catches
// a real hang.
const defaultAsyncUtilTimeout = getConfig().asyncUtilTimeout;
beforeAll(() => configure({ asyncUtilTimeout: 5_000 }));
afterAll(() => configure({ asyncUtilTimeout: defaultAsyncUtilTimeout }));
it("mounts list and detail keys under the installed governed namespace", async () => {
expect(REFERENCE_RESOURCE_QUERY_NAMESPACE).toEqual({
namespaceId: "reference-resource",
+11 -1
View File
@@ -1,7 +1,17 @@
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { cleanup, configure } from "@testing-library/react";
import { afterEach, vi } from "vitest";
// findBy*/waitFor settle on the DOM change itself; their deadline only reports
// a hang. Routes render through React.lazy, and React 19 holds every Suspense
// reveal on a real 300ms timer (FALLBACK_THROTTLE_MS). A route entered through
// a context table and then a lazy page spends 600ms of the 1s default before
// any rendering work, so on a loaded host the default turns into a speed
// requirement. Fake timers cannot shorten it: Testing Library advances only
// Jest's fake timers, and MSW and user-event run on the real clock. Half the
// 10s test timeout still reports a real hang with the DOM dump.
configure({ asyncUtilTimeout: 5_000 });
afterEach(() => {
cleanup();
// A test that fails before its own vi.useRealTimers() must not leave fake