fix(core,basic,ecommerce): 쇼핑 화면 호출 통합 원복·검색 주소 승계·라우트 캐시 갱신 및 상한값 설정 저장 정합

합의되지 않은 구조 변경을 되돌리고, 계획서 전수조사에서 드러난 결함을 처리했다.

쇼핑 화면 호출 통합(F4)은 API 쿼리 튜닝이 아니라 화면 구조 변경이라 원복했다.
레이아웃 9개를 develop 상태로 복원하고 전용 엔드포인트·컨트롤러·문서·테스트를 걷어냈다.
되돌리면 함께 사라지는 비-F4 수정 둘(페이저 has_more_pages 판정 3곳, Icon 크기 클래스
23줄)은 재적용했다. 성능 개선분은 전부 잔존한다.

통합검색 화면 상태를 전역 상태에서 URL 쿼리로 옮겼다. 종전에는 탭·필터·정렬·페이지가
주소에 없어 새로고침·뒤로가기에서 초기화되고 결과를 공유할 수도 없었다. 화면은 정상으로
보이고 콘솔 에러도 없어 코드만으로는 드러나지 않는 형태였다.

확장이 라우트를 추가해도 라우트 캐시가 걸린 사이트에서는 그 주소가 404 가 되던 구멍을
막았다. 훅 캐시와 달리 라우트 캐시에는 스캔 폴백이 없어 예외도 경고도 남지 않는다.
같은 문제를 이미 푼 ConfigCacheHelper 를 미러링해 갱신 지점을 한 곳으로 모았고,
코어 업데이트가 캐시를 비우기만 하고 되살리지 않던 문제도 함께 고쳤다.

상품·페이지 검색이 커서 판정에 페이지 번호를 넘기지 않아, 커서 없이 깊은 페이지를
지목한 딥링크가 조용히 1 페이지를 돌려주던 결함을 고쳤다. 호출 지점을 손으로 열거하는
대신 저장소를 훑는 패리티 테스트로 다음 도메인의 재발을 막는다.

환경설정 고급 탭의 목록 상한값이 저장되지 않던 결함을 고쳤다. 화면·검증·읽기는 모두
있었는데 저장 시 카테고리 분류표가 손으로 열거돼 있어 그 값만 버려지고 있었다. 분류표를
설정 정의에서 도출하도록 바꿔 다음 카테고리가 합류해도 같은 일이 생기지 않게 했다.
범위를 벗어난 값의 안내에 내부 식별자가 노출되던 것도 함께 정리했다.

언어팩 재설치가 활성 팩을 자기 자신과의 슬롯 충돌로 오인해 강등하던 회귀와, CLI 설치가
HTTP 권한 컨텍스트 없이 자동 활성화되는지를 고정하는 테스트를 함께 담았다.
This commit is contained in:
HeuJung committed 2026-08-06 11:13:54 +09:00
1 parent 0d1105abfc
commit 7b859d4200
74 files changed
+2443 -1520

No files matched your search

@@ -0,0 +1,148 @@
/**
* E2E: 총 건수 상한 표기 계약 + 상품 그리드 페이저 (#519)
*
* 총 건수가 상한을 넘으면 서버가 `last_page: null` 을 보낸다. 화면이 그 값을 숫자로
* 잘못 해석하면 페이저가 통째로 사라지거나 "1 / 1" 로 굳는다 — 응답은 정상이고 콘솔
* 에러도 없어 API 테스트로는 드러나지 않는다. 브라우저에서만 드러나는 성질이라
* 여기서 잡는다.
*
* @scenario case=bounded_total_and_product_grid_pager
*
* @effects search_pager_survives_null_last_page,
* search_count_marks_inexact_total,
* product_grid_pager_uses_has_more_pages
*/
import type { Page } from '@playwright/test';
import { test, expect } from '../../fixtures/auth';
/**
* 화면 진입 공통 대기.
*
* `networkidle` 은 폴링이 있는 화면에서 idle 이 되지 않으므로 쓰지 않는다.
*
* @param page 대상 페이지
* @param path 이동할 경로
* @returns void
*/
async function gotoAndSettle(page: Page, path: string): Promise<void> {
await page.goto(path);
await page.waitForLoadState('domcontentloaded');
await acceptCookieConsent(page);
await page.waitForTimeout(1200);
}
/**
* 쿠키 동의 배너를 처리한다.
*
* GDPR 사전 차단(preblocker)이 동의 전까지 데이터 요청을 막으므로, 배너를 남겨 둔 채로는
* "화면이 어떤 API 를 부르는가" 를 관찰할 수 없다. 배너가 없는 사이트에서는 아무 일도 하지 않는다.
*
* @param page 대상 페이지
* @returns void
*/
async function acceptCookieConsent(page: Page): Promise<void> {
const accept = page.getByRole('button', { name: /모두 동의|Accept all/i }).first();
if (await accept.isVisible({ timeout: 3_000 }).catch(() => false)) {
await accept.click();
await page.waitForTimeout(500);
}
}
// 쇼핑 목록 라우트는 '/shop' 이 아니라 '/shop/products' 다 (템플릿 routes.json 기준).
const SHOP_LIST_PATH = '/shop/products';
test.describe('총 건수 상한과 페이지 이동', () => {
// @scenario case=search_response_carries_accuracy_meta
// @effects search_count_marks_inexact_total
test('검색 응답이 총 건수 정확도를 함께 싣는다', async ({ page }) => {
const responsePromise = page.waitForResponse(
(r) => r.url().includes('/api/search?') && r.status() === 200,
{ timeout: 20_000 },
);
await gotoAndSettle(page, '/search?q=' + encodeURIComponent('테스트'));
const body = await (await responsePromise).json();
const data = body?.data;
expect(data, '검색 응답에 data 가 없다').toBeTruthy();
expect(data).toHaveProperty('total_is_exact');
expect(data).toHaveProperty('total_relation');
// 정확도가 true 면 종전 표기 그대로, false 면 "이상" 표기가 붙어야 한다.
// 표기 문구는 로케일에 따라 다르므로 둘 중 하나가 화면에 있는지로 판정한다.
// 본문 전체를 대상으로 하므로 앵커(`$`)를 쓰지 않는다 — 뒤에 다른 문구가 따라온다.
const suffix = data.total_is_exact
? /\d+\s*건|\d+\s*results/i
: /건 이상|\+ results|more than/i;
await expect(page.locator('body')).toContainText(suffix, { timeout: 15_000 });
});
// @scenario case=search_pager_survives_null_last_page
// @effects search_pager_survives_null_last_page
test('마지막 페이지를 모르는 목록에서도 페이저가 사라지지 않는다', async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', (error) => errors.push(error.message));
// 상한 초과 상태는 실데이터로 재현하기 어려우므로 응답을 가로채 주입한다.
// last_page: null + has_more_pages: true 가 이 시나리오의 핵심 입력이다.
await page.route('**/api/search?**', async (route) => {
const response = await route.fetch();
const body = await response.json();
if (body?.data) {
body.data.last_page = null;
body.data.has_more_pages = true;
body.data.total_relation = 'at_least';
body.data.total_is_exact = false;
}
await route.fulfill({ response, json: body });
});
await gotoAndSettle(page, '/search?q=' + encodeURIComponent('테스트'));
expect(errors, '검색 화면 렌더 중 자바스크립트 오류가 발생했다').toEqual([]);
// "다음" 이동 수단이 실제로 화면에 남아 있어야 한다. 이것이 사라지면 상한 초과
// 검색에서 2페이지 이후에 도달할 방법이 없어진다.
const nextControl = page
.locator('button:has(i.fa-chevron-right), a:has(i.fa-chevron-right)')
.first();
await expect(nextControl, '마지막 페이지를 모른다는 이유로 "다음" 이동이 사라졌다')
.toBeVisible({ timeout: 15_000 });
});
});
test.describe('상품 그리드 페이저', () => {
// @scenario case=product_grid_pager_uses_has_more_pages
// @effects product_grid_pager_uses_has_more_pages
test('상품 그리드 페이저가 마지막 페이지를 몰라도 접히지 않는다', async ({ page }) => {
await page.route('**/api/modules/sirsoft-ecommerce/products?**', async (route) => {
const response = await route.fetch();
const body = await response.json().catch(() => null);
if (!body?.data?.pagination) {
return route.fulfill({ response });
}
// 총 건수를 상한까지만 센 응답을 흉내 낸다 — last_page 는 계산할 수 없다
body.data.pagination.last_page = null;
body.data.pagination.has_more_pages = true;
body.data.pagination.total_relation = 'at_least';
body.data.pagination.total_is_exact = false;
return route.fulfill({ response, body: JSON.stringify(body) });
});
await gotoAndSettle(page, SHOP_LIST_PATH);
// last_page 가 null 이라고 페이저가 통째로 사라지면 1페이지 밖 상품에 도달할 방법이 없다
const nextButton = page.locator('button:has(i.fa-chevron-right)').last();
await expect(nextButton).toBeVisible({ timeout: 15_000 });
await expect(nextButton).toBeEnabled();
});
});
@@ -1,270 +0,0 @@
/**
* E2E: 총 건수 상한 표기 계약 + 쇼핑 첫 화면 단일 요청 (#519)
*
* 두 변경 모두 브라우저에서만 드러나는 성질을 갖는다.
*
* (1) 총 건수가 상한을 넘으면 서버가 `last_page: null` 을 보낸다. 화면이 그 값을
* 숫자로 잘못 해석하면 페이저가 통째로 사라지거나 "1 / 1" 로 굳는다 —
* 응답은 정상이고 콘솔 에러도 없어 API 테스트로는 드러나지 않는다.
* (2) 쇼핑 첫 화면은 다섯 묶음을 한 번에 받도록 바꿨다. 레이아웃 바인딩을 한 곳이라도
* 옛 경로에 남겨 두면 그 영역만 조용히 비어 렌더된다.
*
* @scenario case=bounded_total_and_single_storefront_request
*
* @effects search_pager_survives_null_last_page,
* search_count_marks_inexact_total,
* storefront_uses_single_request,
* storefront_sections_render
*/
import type { Page } from '@playwright/test';
import { test, expect } from '../../fixtures/auth';
/**
* 화면 진입 공통 대기.
*
* `networkidle` 은 폴링이 있는 화면에서 idle 이 되지 않으므로 쓰지 않는다.
*
* @param page 대상 페이지
* @param path 이동할 경로
* @returns void
*/
async function gotoAndSettle(page: Page, path: string): Promise<void> {
await page.goto(path);
await page.waitForLoadState('domcontentloaded');
await acceptCookieConsent(page);
await page.waitForTimeout(1200);
}
/**
* 쿠키 동의 배너를 처리한다.
*
* GDPR 사전 차단(preblocker)이 동의 전까지 데이터 요청을 막으므로, 배너를 남겨 둔 채로는
* "화면이 어떤 API 를 부르는가" 를 관찰할 수 없다. 배너가 없는 사이트에서는 아무 일도 하지 않는다.
*
* @param page 대상 페이지
* @returns void
*/
async function acceptCookieConsent(page: Page): Promise<void> {
const accept = page.getByRole('button', { name: /모두 동의|Accept all/i }).first();
if (await accept.isVisible({ timeout: 3_000 }).catch(() => false)) {
await accept.click();
await page.waitForTimeout(500);
}
}
// 쇼핑 목록 라우트는 '/shop' 이 아니라 '/shop/products' 다 (템플릿 routes.json 기준).
const SHOP_LIST_PATH = '/shop/products';
test.describe('총 건수 상한과 페이지 이동', () => {
// @scenario case=search_response_carries_accuracy_meta
// @effects search_count_marks_inexact_total
test('검색 응답이 총 건수 정확도를 함께 싣는다', async ({ page }) => {
const responsePromise = page.waitForResponse(
(r) => r.url().includes('/api/search?') && r.status() === 200,
{ timeout: 20_000 },
);
await gotoAndSettle(page, '/search?q=' + encodeURIComponent('테스트'));
const body = await (await responsePromise).json();
const data = body?.data;
expect(data, '검색 응답에 data 가 없다').toBeTruthy();
expect(data).toHaveProperty('total_is_exact');
expect(data).toHaveProperty('total_relation');
// 정확도가 true 면 종전 표기 그대로, false 면 "이상" 표기가 붙어야 한다.
// 표기 문구는 로케일에 따라 다르므로 둘 중 하나가 화면에 있는지로 판정한다.
// 본문 전체를 대상으로 하므로 앵커(`$`)를 쓰지 않는다 — 뒤에 다른 문구가 따라온다.
const suffix = data.total_is_exact
? /\d+\s*건|\d+\s*results/i
: /건 이상|\+ results|more than/i;
await expect(page.locator('body')).toContainText(suffix, { timeout: 15_000 });
});
// @scenario case=search_pager_survives_null_last_page
// @effects search_pager_survives_null_last_page
test('마지막 페이지를 모르는 목록에서도 페이저가 사라지지 않는다', async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', (error) => errors.push(error.message));
// 상한 초과 상태는 실데이터로 재현하기 어려우므로 응답을 가로채 주입한다.
// last_page: null + has_more_pages: true 가 이 시나리오의 핵심 입력이다.
await page.route('**/api/search?**', async (route) => {
const response = await route.fetch();
const body = await response.json();
if (body?.data) {
body.data.last_page = null;
body.data.has_more_pages = true;
body.data.total_relation = 'at_least';
body.data.total_is_exact = false;
}
await route.fulfill({ response, json: body });
});
await gotoAndSettle(page, '/search?q=' + encodeURIComponent('테스트'));
expect(errors, '검색 화면 렌더 중 자바스크립트 오류가 발생했다').toEqual([]);
// "다음" 이동 수단이 실제로 화면에 남아 있어야 한다. 이것이 사라지면 상한 초과
// 검색에서 2페이지 이후에 도달할 방법이 없어진다.
const nextControl = page
.locator('button:has(i.fa-chevron-right), a:has(i.fa-chevron-right)')
.first();
await expect(nextControl, '마지막 페이지를 모른다는 이유로 "다음" 이동이 사라졌다')
.toBeVisible({ timeout: 15_000 });
});
});
test.describe('쇼핑 첫 화면 단일 요청', () => {
// @scenario case=storefront_uses_single_request
// @effects storefront_uses_single_request
test('분류·상품·진열 묶음을 한 번의 요청으로 받는다', async ({ page }) => {
const productApiCalls: string[] = [];
page.on('request', (request) => {
const url = request.url();
if (/\/api\/modules\/sirsoft-ecommerce\/(products|categories|storefront)/.test(url)) {
productApiCalls.push(url);
}
});
const storefrontPromise = page.waitForResponse(
(r) => r.url().includes('/api/modules/sirsoft-ecommerce/storefront') && r.status() === 200,
{ timeout: 20_000 },
);
await gotoAndSettle(page, SHOP_LIST_PATH);
const body = await (await storefrontPromise).json();
const data = body?.data;
expect(data, 'storefront 응답에 data 가 없다').toBeTruthy();
for (const key of ['categories', 'products', 'recent_products', 'popular_products', 'new_products']) {
expect(data, `storefront 응답에 ${key} 묶음이 없다`).toHaveProperty(key);
}
// 개별 엔드포인트를 함께 부르고 있으면 통합의 의미가 없다.
const legacyCalls = productApiCalls.filter(
(url) => /\/(products\/(popular|new|recent)|categories)(\?|$)/.test(url),
);
expect(legacyCalls, `쇼핑 첫 화면이 개별 엔드포인트를 여전히 호출한다: ${legacyCalls.join(', ')}`).toEqual([]);
});
// @scenario case=storefront_sections_render
// @effects storefront_sections_render
test('첫 화면의 각 영역이 비어 있지 않게 렌더된다', async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', (error) => errors.push(error.message));
const storefrontPromise = page.waitForResponse(
(r) => r.url().includes('/api/modules/sirsoft-ecommerce/storefront') && r.status() === 200,
{ timeout: 20_000 },
);
await gotoAndSettle(page, SHOP_LIST_PATH);
expect(errors, '쇼핑 첫 화면 렌더 중 자바스크립트 오류가 발생했다').toEqual([]);
await expect(page.locator('h1')).toBeVisible({ timeout: 15_000 });
// 통합 응답이 실제로 담아 온 묶음은 화면에도 나타나야 한다. 바인딩 경로가
// 하나라도 옛 이름에 남아 있으면 그 영역만 조용히 비므로, 응답에 항목이 있는
// 묶음에 한해 그 이름이 화면에 렌더됐는지 본다 (빈 사이트에서는 건너뛴다).
const data = (await (await storefrontPromise).json())?.data;
const sections: Array<[string, unknown]> = [
['recent_products', data?.recent_products],
['popular_products', data?.popular_products],
['new_products', data?.new_products],
];
for (const [key, items] of sections) {
const list = Array.isArray(items) ? items : (items as { data?: unknown[] })?.data;
if (!Array.isArray(list) || list.length === 0) {
continue;
}
const firstName = (list[0] as { name_localized?: string; name?: string })?.name_localized
?? (list[0] as { name?: string })?.name;
if (typeof firstName !== 'string' || firstName.trim() === '') {
continue;
}
await expect(
page.getByText(firstName, { exact: false }).first(),
`${key} 묶음이 응답에는 있는데 화면에 렌더되지 않았다 — 바인딩 경로가 어긋났다`,
).toBeVisible({ timeout: 15_000 });
}
});
});
test.describe('공유 partial 을 쓰는 다른 화면 (#519 회귀)', () => {
// 쇼핑 첫 화면을 단일 요청으로 통합하면서, 같은 partial 을 쓰는 분류 화면과 상품
// 상세의 인기 상품 영역이 조용히 비었던 회귀다. `?? []` 폴백 때문에 예외도 404 도
// 나지 않아 브라우저에서 눈으로 보는 것 말고는 드러나지 않는다.
// @scenario case=shared_partial_reads_parent_declared_names
// @effects shared_partial_reads_parent_declared_names
test('분류 화면이 상품 그리드 데이터를 실제로 받는다', async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', (error) => errors.push(error.message));
const listRequests: string[] = [];
page.on('request', (request) => {
const url = request.url();
if (/\/api\/modules\/sirsoft-ecommerce\/(products|storefront)(\?|$|\/)/.test(url)) {
listRequests.push(url);
}
});
// 분류 슬러그가 없는 사이트에서는 목록 화면으로 대체 확인한다
await gotoAndSettle(page, '/shop/products');
expect(errors, '분류/목록 화면 렌더 중 자바스크립트 오류가 발생했다').toEqual([]);
// 이 화면은 공유 partial 로 상품 그리드를 그린다. partial 이 부모가 선언한 이름을
// 읽지 못하면 데이터 요청 자체가 나가지 않고 그리드만 조용히 빈다 — 요청이 실제로
// 있었는지가 그 회귀를 잡는 신호다.
expect(
listRequests,
'상품 목록/통합 응답 요청이 한 번도 나가지 않았다 — 공유 partial 이 부모가 선언한 데이터소스 이름을 읽지 못한다',
).not.toEqual([]);
await expect(page.locator('h1')).toBeVisible({ timeout: 15_000 });
});
// @scenario case=storefront_grid_pager_uses_has_more_pages
// @effects storefront_grid_pager_uses_has_more_pages
test('상품 그리드 페이저가 마지막 페이지를 몰라도 접히지 않는다', async ({ page }) => {
await page.route('**/api/modules/sirsoft-ecommerce/storefront**', async (route) => {
const response = await route.fetch();
const body = await response.json().catch(() => null);
if (!body?.data?.products?.pagination) {
return route.fulfill({ response });
}
// 총 건수를 상한까지만 센 응답을 흉내 낸다 — last_page 는 계산할 수 없다
body.data.products.pagination.last_page = null;
body.data.products.pagination.has_more_pages = true;
body.data.products.pagination.total_relation = 'at_least';
body.data.products.pagination.total_is_exact = false;
return route.fulfill({ response, body: JSON.stringify(body) });
});
await gotoAndSettle(page, SHOP_LIST_PATH);
// last_page 가 null 이라고 페이저가 통째로 사라지면 1페이지 밖 상품에 도달할 방법이 없다
const nextButton = page.locator('button:has(i.fa-chevron-right)').last();
await expect(nextButton).toBeVisible({ timeout: 15_000 });
await expect(nextButton).toBeEnabled();
});
});
@@ -0,0 +1,184 @@
/**
* E2E: 통합검색 화면 상태의 주소 승계 (#519)
*
* 탭·게시판필터·정렬·페이지는 전역 상태가 아니라 URL 쿼리가 SSoT 여야 한다.
* 전역 상태에만 두면 화면은 정상으로 보이고 콘솔 에러도 없지만, 주소가 바뀌지 않아
*
* - 새로고침하면 검색어만 남고 나머지가 초기값으로 돌아가고,
* - 뒤로가기가 직전에 보던 탭·페이지로 되돌아가지 못하며,
* - 보고 있던 결과를 주소로 공유할 수 없다.
*
* 셋 다 브라우저의 주소·히스토리를 실제로 움직여야만 드러나므로 단위 테스트로는
* 잡히지 않는다. 레이아웃 계약 단위 검사는
* `templates/_bundled/sirsoft-basic/__tests__/layouts/search-url-state-contract.test.ts` 가 맡는다.
*
* @scenario case=search_state_round_trips_through_url
*
* @effects search_state_persists_in_url,
* search_state_survives_reload,
* search_state_restores_on_back,
* search_new_keyword_resets_state
*/
import type { Page } from '@playwright/test';
import { test, expect } from '../../fixtures/auth';
const KEYWORD = '테스트';
const SEARCH_PATH = '/search?q=' + encodeURIComponent(KEYWORD);
/**
* 화면 진입 공통 대기.
*
* `networkidle` 은 폴링이 있는 화면에서 idle 이 되지 않으므로 쓰지 않는다.
*
* @param page 대상 페이지
* @param path 이동할 경로
* @returns void
*/
async function gotoAndSettle(page: Page, path: string): Promise<void> {
await page.goto(path);
await page.waitForLoadState('domcontentloaded');
await acceptCookieConsent(page);
await page.waitForTimeout(1200);
}
/**
* 쿠키 동의 배너를 처리한다.
*
* 동의 전에는 사전 차단이 데이터 요청을 막아 검색 결과가 그려지지 않는다.
* 배너가 없는 사이트에서는 아무 일도 하지 않는다.
*
* @param page 대상 페이지
* @returns void
*/
async function acceptCookieConsent(page: Page): Promise<void> {
const accept = page.getByRole('button', { name: /모두 동의|Accept all/i }).first();
if (await accept.isVisible({ timeout: 3_000 }).catch(() => false)) {
await accept.click();
await page.waitForTimeout(500);
}
}
/**
* 게시글 탭 버튼을 반환합니다.
*
* @param page 대상 페이지
* @returns 게시글 탭 로케이터
*/
function postsTab(page: Page) {
return page.getByRole('button', { name: /게시글|Posts/i }).first();
}
/**
* 현재 주소의 쿼리 파라미터를 읽습니다.
*
* @param page 대상 페이지
* @returns 쿼리 파라미터 객체
*/
async function queryParams(page: Page): Promise<Record<string, string>> {
const url = new URL(page.url());
return Object.fromEntries(url.searchParams.entries());
}
test.describe('통합검색 화면 상태의 주소 승계', () => {
// @scenario case=search_state_persists_in_url
// @effects search_state_persists_in_url
test('탭을 바꾸면 주소에 남고 검색어는 유지된다', async ({ page }) => {
await gotoAndSettle(page, SEARCH_PATH);
const tab = postsTab(page);
// 탭이 없는 사이트(검색 결과 0건 등)에서는 이 축을 잴 수 없다.
if (!(await tab.isVisible({ timeout: 5_000 }).catch(() => false))) {
test.skip(true, '검색 탭이 화면에 없어 상태 승계를 측정할 수 없다');
}
await tab.click();
await page.waitForTimeout(800);
const params = await queryParams(page);
expect(params.type, '탭 전환이 주소에 반영되지 않았다').toBe('posts');
expect(params.q, '탭을 바꿨더니 검색어가 주소에서 사라졌다').toBe(KEYWORD);
// 결과 집합이 달라지므로 이전 페이지·커서는 따라오면 안 된다.
expect(params.page, '탭 전환인데 이전 페이지 번호가 남았다').toBeUndefined();
expect(params.cursor, '탭 전환인데 이전 커서가 남았다').toBeUndefined();
});
// @scenario case=search_state_survives_reload
// @effects search_state_survives_reload
test('새로고침해도 보고 있던 탭이 유지된다', async ({ page }) => {
await gotoAndSettle(page, SEARCH_PATH + '&type=posts');
const before = await queryParams(page);
expect(before.type, '사전 조건: 주소에 탭이 실려 있어야 한다').toBe('posts');
await page.reload();
await page.waitForLoadState('domcontentloaded');
await page.waitForTimeout(1200);
const after = await queryParams(page);
expect(after.type, '새로고침 후 탭이 초기값으로 돌아갔다').toBe('posts');
expect(after.q, '새로고침 후 검색어가 사라졌다').toBe(KEYWORD);
// 주소만 남고 화면이 따라오지 않으면 의미가 없다 — 요청도 그 탭으로 나가야 한다.
const request = await page
.waitForRequest((r) => r.url().includes('/api/search?') && r.url().includes('type=posts'), {
timeout: 15_000,
})
.catch(() => null);
expect(request, '새로고침 후 검색 요청이 주소의 탭을 반영하지 않았다').not.toBeNull();
});
// @scenario case=search_state_restores_on_back
// @effects search_state_restores_on_back
test('뒤로가기가 직전에 보던 탭으로 되돌아간다', async ({ page }) => {
await gotoAndSettle(page, SEARCH_PATH);
const tab = postsTab(page);
if (!(await tab.isVisible({ timeout: 5_000 }).catch(() => false))) {
test.skip(true, '검색 탭이 화면에 없어 히스토리 왕복을 측정할 수 없다');
}
await tab.click();
await page.waitForTimeout(800);
expect((await queryParams(page)).type, '사전 조건: 탭 전환이 주소에 반영돼야 한다').toBe('posts');
await page.goBack();
await page.waitForTimeout(800);
const params = await queryParams(page);
// 탭 전환이 history 항목을 만들지 않으면 뒤로가기가 검색 화면 자체를 떠난다.
expect(params.q, '뒤로가기가 검색 화면을 벗어났다').toBe(KEYWORD);
expect(params.type, '뒤로가기 후에도 바뀐 탭이 그대로다').toBeUndefined();
});
// @scenario case=search_new_keyword_resets_state
// @effects search_new_keyword_resets_state
test('검색어를 새로 실행하면 이전 조건이 따라오지 않는다', async ({ page }) => {
await gotoAndSettle(page, SEARCH_PATH + '&type=posts&sort=latest&page=2');
const input = page.locator('input[name="q"]').first();
if (!(await input.isVisible({ timeout: 5_000 }).catch(() => false))) {
test.skip(true, '검색 입력란이 화면에 없어 재검색을 측정할 수 없다');
}
await input.fill('다른검색어');
await input.press('Enter');
await page.waitForTimeout(1200);
const params = await queryParams(page);
expect(params.q, '새 검색어가 주소에 반영되지 않았다').toBe('다른검색어');
// 의도적 리셋이다 — 결과 집합 자체가 달라지므로 이전 조건을 물려받지 않는다.
expect(params.type, '새 검색인데 이전 탭이 따라왔다').toBeUndefined();
expect(params.sort, '새 검색인데 이전 정렬이 따라왔다').toBeUndefined();
expect(params.page, '새 검색인데 이전 페이지가 따라왔다').toBeUndefined();
});
});