v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
+29
-21
@@ -1,13 +1,16 @@
|
||||
/**
|
||||
* @file board-401-error-handling.test.tsx
|
||||
* @description 게시판 목록/상세 - 비로그인 접근 시 401 errorHandling 검증 (이슈 #228 B-5)
|
||||
* @description 게시판 목록/상세 - 비로그인 접근 시 401 errorHandling 검증 (이슈 #228 B-5, #413 item 28)
|
||||
*
|
||||
* 검증 항목:
|
||||
* 1. show.json / index.json 데이터소스에 401 errorHandling이 정의되어 있는가
|
||||
* 2. 401 핸들러가 sequence(toast → navigate /login?redirect=...) 방식인가
|
||||
* 3. navigate params에 redirect 쿼리가 포함되어 있는가
|
||||
* 2. 401 핸들러가 sequence(toast → redirectToLoginWithReturn) 방식인가
|
||||
* 3. 두 번째 action 이 redirectToLoginWithReturn 핸들러인가 (custom+name 형식 금지)
|
||||
* 4. auth_required가 아닌 auth_mode: "optional"이 사용되는가
|
||||
* 5. 기존 403/404 핸들러가 유지되는가
|
||||
*
|
||||
* @scenario entry_point:board_list_401,board_show_401
|
||||
* @effects redirect_preserves_pathname,login_returns_to_original_path
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
@@ -52,19 +55,23 @@ describe('게시판 401 errorHandling — sequence + redirect 방식 (이슈 #22
|
||||
expect(toastAction?.handler).toBe('toast');
|
||||
});
|
||||
|
||||
it('두 번째 action이 navigate 핸들러이어야 한다', () => {
|
||||
const navigateAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(navigateAction?.handler).toBe('navigate');
|
||||
it('두 번째 action이 redirectToLoginWithReturn 핸들러이어야 한다', () => {
|
||||
// 등록 키를 handler 에 직접 지정 (custom+name 형식은 디스패치가 handler 값으로만
|
||||
// 조회하므로 throw 됨 — feedback_verify_full_path_not_just_evaluator).
|
||||
const redirectAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(redirectAction?.handler).toBe('redirectToLoginWithReturn');
|
||||
});
|
||||
|
||||
it('navigate path가 /login이어야 한다', () => {
|
||||
const navigateAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(navigateAction?.params?.path).toBe('/login');
|
||||
it('두 번째 action에 name 필드 단언이 없어야 한다 (custom+name 거짓 통과 방지)', () => {
|
||||
const redirectAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(redirectAction?.handler).not.toBe('custom');
|
||||
expect((redirectAction as any)?.name).toBeUndefined();
|
||||
});
|
||||
|
||||
it('navigate query에 redirect 파라미터가 없어야 한다', () => {
|
||||
const navigateAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(navigateAction?.params?.query).toBeUndefined();
|
||||
it('redirect 는 핸들러가 window.location 으로 캡처하므로 navigate params 가 불필요하다', () => {
|
||||
// 레이아웃에 정적 redirect 표현식을 두지 않는다 (핸들러가 런타임에 캡처).
|
||||
const redirectAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(redirectAction?.params).toBeUndefined();
|
||||
});
|
||||
|
||||
it('기존 403 핸들러가 유지되어야 한다', () => {
|
||||
@@ -109,19 +116,20 @@ describe('게시판 401 errorHandling — sequence + redirect 방식 (이슈 #22
|
||||
expect(toastAction?.handler).toBe('toast');
|
||||
});
|
||||
|
||||
it('두 번째 action이 navigate 핸들러이어야 한다', () => {
|
||||
const navigateAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(navigateAction?.handler).toBe('navigate');
|
||||
it('두 번째 action이 redirectToLoginWithReturn 핸들러이어야 한다', () => {
|
||||
const redirectAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(redirectAction?.handler).toBe('redirectToLoginWithReturn');
|
||||
});
|
||||
|
||||
it('navigate path가 /login이어야 한다', () => {
|
||||
const navigateAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(navigateAction?.params?.path).toBe('/login');
|
||||
it('두 번째 action에 name 필드 단언이 없어야 한다 (custom+name 거짓 통과 방지)', () => {
|
||||
const redirectAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(redirectAction?.handler).not.toBe('custom');
|
||||
expect((redirectAction as any)?.name).toBeUndefined();
|
||||
});
|
||||
|
||||
it('navigate query에 redirect 파라미터가 없어야 한다', () => {
|
||||
const navigateAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(navigateAction?.params?.query).toBeUndefined();
|
||||
it('redirect 는 핸들러가 window.location 으로 캡처하므로 navigate params 가 불필요하다', () => {
|
||||
const redirectAction = dsErrorHandling?.['401']?.actions[1];
|
||||
expect(redirectAction?.params).toBeUndefined();
|
||||
});
|
||||
|
||||
it('기존 403 핸들러가 유지되어야 한다', () => {
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* @file board-gallery-view-count-toggle.test.tsx
|
||||
* @description 갤러리형 목록 - 조회수 표시 토글(show_view_count) 반영 회귀 테스트 (#413-19-4b)
|
||||
*
|
||||
* 배경:
|
||||
* 갤러리형 목록(types/gallery/index.json)의 조회수 Span 에 show_view_count 조건이 없어,
|
||||
* 환경설정에서 '조회수 표시'를 OFF 해도 갤러리형에서는 조회수가 항상 표시되던 회귀.
|
||||
* basic/card 형은 동일 조건으로 정상 동작 → 갤러리에도 동일 if 조건을 추가.
|
||||
*
|
||||
* 검증 항목:
|
||||
* 1. show_view_count !== false 일 때 조회수 표시 (true / 미설정 모두)
|
||||
* 2. show_view_count === false 일 때 조회수 미표시
|
||||
*
|
||||
* 조건식: "{{posts?.data?.board?.settings?.show_view_count !== false}}"
|
||||
* - basic/card/index.json 과 동일 (SSoT)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
|
||||
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
|
||||
|
||||
// ============================================================
|
||||
// 테스트용 컴포넌트 정의
|
||||
// ============================================================
|
||||
|
||||
const TestDiv: React.FC<{
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
'data-testid'?: string;
|
||||
}> = ({ className, children, 'data-testid': testId }) => (
|
||||
<div className={className} data-testid={testId}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
const TestSpan: React.FC<{
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
text?: string;
|
||||
'data-testid'?: string;
|
||||
}> = ({ className, children, text, 'data-testid': testId }) => (
|
||||
<span className={className} data-testid={testId}>
|
||||
{children || text}
|
||||
</span>
|
||||
);
|
||||
|
||||
const TestIcon: React.FC<{
|
||||
name?: string;
|
||||
size?: string;
|
||||
className?: string;
|
||||
}> = ({ name, size, className }) => (
|
||||
<i className={className} data-icon={name} data-size={size} />
|
||||
);
|
||||
|
||||
// ============================================================
|
||||
// 컴포넌트 레지스트리 설정
|
||||
// ============================================================
|
||||
|
||||
function setupTestRegistry(): ComponentRegistry {
|
||||
const registry = ComponentRegistry.getInstance();
|
||||
|
||||
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
|
||||
|
||||
(registry as any).registry = {
|
||||
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
|
||||
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
|
||||
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
|
||||
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
|
||||
};
|
||||
|
||||
return registry;
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 레이아웃 JSON — gallery/index.json 의 조회수 Span 구조를 반영
|
||||
// ============================================================
|
||||
|
||||
const galleryViewCountLayoutJson = {
|
||||
version: '1.0.0',
|
||||
layout_name: 'board_gallery_view_count_test',
|
||||
components: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
props: { 'data-testid': 'meta-area' },
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Span',
|
||||
if: '{{posts?.data?.board?.settings?.show_view_count !== false}}',
|
||||
props: {
|
||||
'data-testid': 'view-count',
|
||||
className:
|
||||
"flex items-center gap-0.5 {{(_local.post?.status === 'blinded' || _local.post?.deleted_at) ? 'text-gray-400' : 'text-gray-300'}}",
|
||||
},
|
||||
children: [
|
||||
{ type: 'basic', name: 'Icon', props: { name: 'eye', size: 'xs' } },
|
||||
{ type: 'basic', name: 'Span', text: '{{_local.post?.view_count ?? 0}}' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// ============================================================
|
||||
// 테스트
|
||||
// ============================================================
|
||||
|
||||
// @scenario board-gallery-view-count
|
||||
// @axes show_view_count=true show_view_count=false show_view_count=unset board_type=gallery
|
||||
// @effects gallery_shows_view_count_when_true, gallery_shows_view_count_when_unset,
|
||||
// gallery_hides_view_count_when_false, gallery_matches_basic_and_card_condition
|
||||
describe('갤러리형 목록 - 조회수 표시 토글(show_view_count) (#413-19-4b)', () => {
|
||||
let registry: ComponentRegistry;
|
||||
|
||||
beforeEach(() => {
|
||||
registry = setupTestRegistry();
|
||||
});
|
||||
|
||||
// @scenario show_view_count=true, board_type=gallery
|
||||
// @effects gallery_shows_view_count_when_true, gallery_matches_basic_and_card_condition
|
||||
it('show_view_count=true 이면 조회수가 표시된다', async () => {
|
||||
const testUtils = createLayoutTest(galleryViewCountLayoutJson, {
|
||||
componentRegistry: registry,
|
||||
initialData: { posts: { data: { board: { settings: { show_view_count: true } } } } },
|
||||
initialState: {
|
||||
_local: { post: { id: 1, view_count: 123, status: 'published', deleted_at: null } },
|
||||
},
|
||||
});
|
||||
|
||||
await testUtils.render();
|
||||
expect(screen.getByTestId('view-count')).toBeTruthy();
|
||||
testUtils.cleanup();
|
||||
});
|
||||
|
||||
// @scenario show_view_count=unset, board_type=gallery
|
||||
// @effects gallery_shows_view_count_when_unset
|
||||
it('show_view_count 미설정(undefined)이면 조회수가 표시된다 (기본 노출)', async () => {
|
||||
const testUtils = createLayoutTest(galleryViewCountLayoutJson, {
|
||||
componentRegistry: registry,
|
||||
initialData: { posts: { data: { board: { settings: {} } } } },
|
||||
initialState: {
|
||||
_local: { post: { id: 2, view_count: 45, status: 'published', deleted_at: null } },
|
||||
},
|
||||
});
|
||||
|
||||
await testUtils.render();
|
||||
expect(screen.getByTestId('view-count')).toBeTruthy();
|
||||
testUtils.cleanup();
|
||||
});
|
||||
|
||||
// @scenario show_view_count=false, board_type=gallery
|
||||
// @effects gallery_hides_view_count_when_false, gallery_matches_basic_and_card_condition
|
||||
it('show_view_count=false 이면 조회수가 표시되지 않는다 (회귀 차단)', async () => {
|
||||
const testUtils = createLayoutTest(galleryViewCountLayoutJson, {
|
||||
componentRegistry: registry,
|
||||
initialData: { posts: { data: { board: { settings: { show_view_count: false } } } } },
|
||||
initialState: {
|
||||
_local: { post: { id: 3, view_count: 999, status: 'published', deleted_at: null } },
|
||||
},
|
||||
});
|
||||
|
||||
await testUtils.render();
|
||||
expect(screen.queryByTestId('view-count')).toBeNull();
|
||||
testUtils.cleanup();
|
||||
});
|
||||
});
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* @file board-post-navigation-list-return.test.tsx
|
||||
* @description 게시판 목록 복귀 상태 보존(45-1) + 답글 상세 이전/다음 버튼 미렌더(47-4) 렌더링 회귀 테스트
|
||||
*
|
||||
* 검증 항목:
|
||||
* 1. 행 클릭(basic/card/gallery) navigate 가 mergeQuery:true 로 현재 목록 query(category/search/page/del/filters)를
|
||||
* 상세 URL 에 부착한다. (45-1)
|
||||
* 2. 상세 '목록' 버튼 navigate 가 mergeQuery:true 로 상세 URL 에 실린 목록 상태를 그대로 목록으로 복귀한다. (45-1)
|
||||
* 3. 답글 상세(navigation prev/next null) 에서는 이전/다음 버튼이 미렌더링된다. (47-4)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
|
||||
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
|
||||
|
||||
// ============================================================
|
||||
// 테스트용 컴포넌트 정의
|
||||
// ============================================================
|
||||
|
||||
const TestDiv: React.FC<{
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
'data-testid'?: string;
|
||||
}> = ({ className, children, 'data-testid': testId }) => (
|
||||
<div className={className} data-testid={testId}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
const TestButton: React.FC<{
|
||||
type?: string;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
'data-testid'?: string;
|
||||
onClick?: () => void;
|
||||
}> = ({ type, className, children, 'data-testid': testId, onClick }) => (
|
||||
<button type={type as any} className={className} data-testid={testId} onClick={onClick}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
|
||||
const TestSpan: React.FC<{
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
text?: string;
|
||||
'data-testid'?: string;
|
||||
}> = ({ className, children, text, 'data-testid': testId }) => (
|
||||
<span className={className} data-testid={testId}>
|
||||
{children || text}
|
||||
</span>
|
||||
);
|
||||
|
||||
const TestIcon: React.FC<{ name?: string; size?: string }> = ({ name }) => (
|
||||
<i data-icon={name} />
|
||||
);
|
||||
|
||||
function setupTestRegistry(): ComponentRegistry {
|
||||
const registry = ComponentRegistry.getInstance();
|
||||
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
|
||||
(registry as any).registry = {
|
||||
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
|
||||
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
|
||||
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
|
||||
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
|
||||
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'composite' } },
|
||||
};
|
||||
return registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 URL(window.location)을 목록/상세 상태로 설정합니다.
|
||||
* navigate 핸들러의 mergeQuery 는 window.location.search 를 읽어 병합합니다.
|
||||
*/
|
||||
function setUrl(search: string): void {
|
||||
window.history.replaceState({}, '', `/board/free${search}`);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 45-1: 행 클릭 → 상세 URL 에 목록 상태 부착 (mergeQuery)
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* @scenario post_kind=original
|
||||
* @effects list_return_preserves_query
|
||||
*/
|
||||
describe('45-1 행 클릭 시 목록 상태(query)를 상세 URL 에 부착', () => {
|
||||
beforeEach(() => {
|
||||
setupTestRegistry();
|
||||
});
|
||||
afterEach(() => {
|
||||
window.history.replaceState({}, '', '/');
|
||||
});
|
||||
|
||||
const rowClickLayout = {
|
||||
version: '1.0.0',
|
||||
layout_name: 'board_row_click_test',
|
||||
data_sources: [],
|
||||
components: [
|
||||
{
|
||||
comment: '행 클릭 시 현재 목록 상태를 상세 URL 에 부착 (45-1)',
|
||||
type: 'basic',
|
||||
name: 'Button',
|
||||
props: { 'data-testid': 'row' },
|
||||
actions: [
|
||||
{
|
||||
type: 'click',
|
||||
handler: 'navigate',
|
||||
params: { path: '/board/free/77', mergeQuery: true, query: {} },
|
||||
},
|
||||
],
|
||||
text: 'row',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it('목록 query(category/search/page)가 상세 navigate 경로에 보존된다', async () => {
|
||||
setUrl('?category=공지&search=테스트&page=2');
|
||||
|
||||
const testUtils = createLayoutTest(rowClickLayout);
|
||||
await testUtils.render();
|
||||
|
||||
await testUtils.triggerAction({
|
||||
type: 'click',
|
||||
handler: 'navigate',
|
||||
params: { path: '/board/free/77', mergeQuery: true, query: {} },
|
||||
} as any);
|
||||
|
||||
const history = testUtils.getNavigationHistory();
|
||||
expect(history.length).toBe(1);
|
||||
const dest = history[0];
|
||||
expect(dest.startsWith('/board/free/77')).toBe(true);
|
||||
expect(dest).toContain('category=%EA%B3%B5%EC%A7%80'); // '공지' URL 인코딩
|
||||
expect(dest).toContain('search=%ED%85%8C%EC%8A%A4%ED%8A%B8'); // '테스트'
|
||||
expect(dest).toContain('page=2');
|
||||
|
||||
testUtils.cleanup();
|
||||
});
|
||||
|
||||
it('del=1(권한자 토글)도 상세 URL 로 함께 전달된다', async () => {
|
||||
setUrl('?del=1&page=3');
|
||||
|
||||
const testUtils = createLayoutTest(rowClickLayout);
|
||||
await testUtils.render();
|
||||
|
||||
await testUtils.triggerAction({
|
||||
type: 'click',
|
||||
handler: 'navigate',
|
||||
params: { path: '/board/free/77', mergeQuery: true, query: {} },
|
||||
} as any);
|
||||
|
||||
const dest = testUtils.getNavigationHistory()[0];
|
||||
expect(dest).toContain('del=1');
|
||||
expect(dest).toContain('page=3');
|
||||
|
||||
testUtils.cleanup();
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 45-1: 상세 '목록' 버튼 → 목록 상태 복귀
|
||||
// ============================================================
|
||||
|
||||
describe("45-1 '목록' 버튼이 상세 URL 의 목록 상태를 목록으로 복귀", () => {
|
||||
beforeEach(() => {
|
||||
setupTestRegistry();
|
||||
});
|
||||
afterEach(() => {
|
||||
window.history.replaceState({}, '', '/');
|
||||
});
|
||||
|
||||
it('상세 URL 의 query 가 목록 경로로 그대로 복귀된다', async () => {
|
||||
// 상세 화면 URL 에 목록 상태가 실려 있음
|
||||
window.history.replaceState({}, '', '/board/free/77?category=공지&search=테스트&page=2');
|
||||
|
||||
const listButtonLayout = {
|
||||
version: '1.0.0',
|
||||
layout_name: 'board_list_button_test',
|
||||
data_sources: [],
|
||||
components: [
|
||||
{
|
||||
comment: '목록으로 버튼 (45-1)',
|
||||
type: 'basic',
|
||||
name: 'Button',
|
||||
props: { 'data-testid': 'back-to-list' },
|
||||
actions: [
|
||||
{
|
||||
type: 'click',
|
||||
handler: 'navigate',
|
||||
params: { path: '/board/free', mergeQuery: true, query: {} },
|
||||
},
|
||||
],
|
||||
text: 'list',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const testUtils = createLayoutTest(listButtonLayout);
|
||||
await testUtils.render();
|
||||
|
||||
await testUtils.triggerAction({
|
||||
type: 'click',
|
||||
handler: 'navigate',
|
||||
params: { path: '/board/free', mergeQuery: true, query: {} },
|
||||
} as any);
|
||||
|
||||
const dest = testUtils.getNavigationHistory()[0];
|
||||
expect(dest.startsWith('/board/free?')).toBe(true);
|
||||
expect(dest).toContain('category=%EA%B3%B5%EC%A7%80');
|
||||
expect(dest).toContain('search=%ED%85%8C%EC%8A%A4%ED%8A%B8');
|
||||
expect(dest).toContain('page=2');
|
||||
|
||||
testUtils.cleanup();
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 47-4: 답글 상세 → 이전/다음 버튼 미렌더
|
||||
// ============================================================
|
||||
|
||||
describe('47-4 답글 상세에서 이전/다음 버튼 미렌더', () => {
|
||||
beforeEach(() => {
|
||||
setupTestRegistry();
|
||||
});
|
||||
|
||||
// _navigation.json 의 이전/다음 버튼 if 조건 구조를 그대로 재현
|
||||
const navButtonsLayout = {
|
||||
version: '1.0.0',
|
||||
layout_name: 'board_nav_buttons_test',
|
||||
data_sources: [
|
||||
{
|
||||
id: 'navigation',
|
||||
type: 'api',
|
||||
endpoint: '/api/modules/sirsoft-board/boards/free/posts/77/navigation',
|
||||
method: 'GET',
|
||||
auto_fetch: true,
|
||||
},
|
||||
],
|
||||
components: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
children: [
|
||||
{
|
||||
comment: '이전글 버튼',
|
||||
type: 'basic',
|
||||
name: 'Button',
|
||||
if: '{{navigation?.data?.prev?.id}}',
|
||||
props: { 'data-testid': 'nav-prev' },
|
||||
text: 'prev',
|
||||
},
|
||||
{
|
||||
comment: '다음글 버튼',
|
||||
type: 'basic',
|
||||
name: 'Button',
|
||||
if: '{{navigation?.data?.next?.id}}',
|
||||
props: { 'data-testid': 'nav-next' },
|
||||
text: 'next',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it('답글 상세(navigation prev/next null) → 이전/다음 버튼 모두 미렌더', async () => {
|
||||
const testUtils = createLayoutTest(navButtonsLayout);
|
||||
testUtils.mockApi('navigation', {
|
||||
response: { data: { prev: null, next: null } },
|
||||
});
|
||||
await testUtils.render();
|
||||
|
||||
expect(screen.queryByTestId('nav-prev')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('nav-next')).not.toBeInTheDocument();
|
||||
|
||||
testUtils.cleanup();
|
||||
});
|
||||
|
||||
it('원글 상세(navigation prev/next 존재) → 이전/다음 버튼 렌더 (대조군)', async () => {
|
||||
const testUtils = createLayoutTest(navButtonsLayout);
|
||||
testUtils.mockApi('navigation', {
|
||||
response: { data: { prev: { id: 76 }, next: { id: 78 } } },
|
||||
});
|
||||
await testUtils.render();
|
||||
|
||||
expect(screen.getByTestId('nav-prev')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('nav-next')).toBeInTheDocument();
|
||||
|
||||
testUtils.cleanup();
|
||||
});
|
||||
});
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* @file board-report-modal-feedback.test.tsx
|
||||
* @description 신고 모달 - 제출 후 피드백/상태 반영 검증 (이슈 #413-60)
|
||||
*
|
||||
* 검수 결과(김은혜, 오류확정):
|
||||
* - 증상2: 신고 성공 후 버튼이 "신고됨"으로 즉시 안 바뀜 (새로고침해야 전환)
|
||||
* - 증상1: 신고 실패(409 등) 시 spinner만 잠깐, 모달 안 닫힘 + 에러 토스트 미노출 → "진행 불가"
|
||||
*
|
||||
* 근본 원인 / 수정:
|
||||
* - 증상2: onSuccess 에 post 데이터소스 refetch 누락 → refetchDataSource(post) 추가
|
||||
* - 증상1: onError 에 closeModal 누락 → "모달 닫고 토스트"(PO 결정) 로 보강
|
||||
*
|
||||
* 신고 모달은 게시글/댓글 공용 1파일이므로 이 단언이 양쪽을 모두 커버한다.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import reportModal from '../../../layouts/partials/board/show/modals/_modal_report.json';
|
||||
|
||||
/**
|
||||
* 신고 모달의 "신고하기" 제출 버튼 액션을 찾는다.
|
||||
* 버튼 영역 → conditions 핸들러 → 검증 통과(then 배열) 안의 apiCall 을 반환.
|
||||
*/
|
||||
function findSubmitApiCall(layout: any): any {
|
||||
const found: any[] = [];
|
||||
|
||||
function walk(node: any) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach(walk);
|
||||
return;
|
||||
}
|
||||
if (node.handler === 'apiCall') {
|
||||
found.push(node);
|
||||
}
|
||||
for (const key of Object.keys(node)) {
|
||||
walk(node[key]);
|
||||
}
|
||||
}
|
||||
|
||||
walk(layout);
|
||||
// 신고 제출 apiCall: target 이 reportModal.apiEndpoint 인 것
|
||||
return found.find(
|
||||
(a) => typeof a.target === 'string' && a.target.includes('reportModal')
|
||||
) ?? found[0] ?? null;
|
||||
}
|
||||
|
||||
function asArray(x: any): any[] {
|
||||
if (!x) return [];
|
||||
return Array.isArray(x) ? x : [x];
|
||||
}
|
||||
|
||||
describe('신고 모달 제출 피드백 (이슈 #413-60)', () => {
|
||||
const apiCall = findSubmitApiCall(reportModal);
|
||||
|
||||
it('신고 제출 apiCall 액션을 찾을 수 있어야 한다', () => {
|
||||
expect(apiCall).not.toBeNull();
|
||||
expect(apiCall.handler).toBe('apiCall');
|
||||
expect(apiCall.params?.method).toBe('POST');
|
||||
});
|
||||
|
||||
describe('증상2 — onSuccess 에 post 데이터소스 refetch 가 포함되어야 한다', () => {
|
||||
const onSuccess = asArray(apiCall?.onSuccess);
|
||||
|
||||
it('onSuccess 에 refetchDataSource 핸들러가 있어야 한다', () => {
|
||||
const refetch = onSuccess.find((a) => a.handler === 'refetchDataSource');
|
||||
expect(refetch).toBeDefined();
|
||||
});
|
||||
|
||||
it('refetchDataSource 가 post 데이터소스를 대상으로 해야 한다 (params.dataSourceId)', () => {
|
||||
const refetch = onSuccess.find((a) => a.handler === 'refetchDataSource');
|
||||
expect(refetch?.params?.dataSourceId).toBe('post');
|
||||
});
|
||||
|
||||
it('onSuccess 에 성공 토스트가 유지되어야 한다', () => {
|
||||
const toast = onSuccess.find((a) => a.handler === 'toast');
|
||||
expect(toast?.params?.type).toBe('success');
|
||||
});
|
||||
|
||||
it('onSuccess 에 closeModal 이 유지되어야 한다', () => {
|
||||
const close = onSuccess.find((a) => a.handler === 'closeModal');
|
||||
expect(close).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('증상1 — onError 에 모달 닫기 + 에러 토스트가 포함되어야 한다 (모달 닫고 토스트)', () => {
|
||||
const onError = asArray(apiCall?.onError);
|
||||
|
||||
it('onError 에 reportSubmitting 리셋(setState)이 있어야 한다', () => {
|
||||
const reset = onError.find(
|
||||
(a) => a.handler === 'setState' && 'reportSubmitting' in (a.params ?? {})
|
||||
);
|
||||
expect(reset).toBeDefined();
|
||||
expect(reset?.params?.reportSubmitting).toBe(false);
|
||||
});
|
||||
|
||||
it('onError 에 에러 토스트가 있어야 한다', () => {
|
||||
const toast = onError.find((a) => a.handler === 'toast');
|
||||
expect(toast).toBeDefined();
|
||||
expect(toast?.params?.type).toBe('error');
|
||||
});
|
||||
|
||||
it('onError 에 closeModal 이 있어야 한다 (PO 결정: 실패 시 모달 닫고 토스트)', () => {
|
||||
const close = onError.find((a) => a.handler === 'closeModal');
|
||||
expect(close).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -159,9 +159,12 @@ describe('show.json - SEO meta 설정', () => {
|
||||
expect(ogDesc).toContain('_seo');
|
||||
});
|
||||
|
||||
it('structured_data.headline이 _seo 컨텍스트를 참조한다', () => {
|
||||
const headline = seo.structured_data?.headline ?? '';
|
||||
expect(headline).toContain('_seo');
|
||||
// structured_data 는 show.json 정적 선언이 아니라 백엔드(module.php seoStructuredData)가
|
||||
// 런타임에 게시글 데이터로 Article 스키마(headline=post.subject 등)를 동적 주입한다. og 는
|
||||
// show.json 에 _seo 폴백을 정적 선언하지만 structured_data 는 주입 구조라 정적 키가 없는 게
|
||||
// 정상이다. 편집기용 경로 메타(seoStructuredDataMeta)는 BoardModuleSeoTest 에서 검증한다.
|
||||
it('structured_data 는 show.json 정적 선언 없음(백엔드 module.php 가 런타임 주입)', () => {
|
||||
expect(seo.structured_data).toBeUndefined();
|
||||
});
|
||||
|
||||
it('data_sources에 post가 정의된다', () => {
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* @file checkout-mileage-error-message.test.tsx
|
||||
* @description 마일리지 적용 실패 토스트 메시지 바인딩 검증 (U15 후속)
|
||||
*
|
||||
* 배경: 보유 마일리지 초과 사용 시 백엔드는 422 + errors.{code,message}(구체 안내)를
|
||||
* 내려보내는데, 프론트 onError 토스트가 상단 generic message(error.message)만 노출해
|
||||
* "주문서 수정에 실패했습니다"만 보이던 결함. error.errors?.message 우선 fallback 으로 정정.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import mileagePartial from '../../../layouts/partials/shop/_checkout_mileage.json';
|
||||
|
||||
/**
|
||||
* JSON 트리에서 조건을 만족하는 첫 노드를 재귀 탐색한다.
|
||||
*/
|
||||
function findNode(obj: any, predicate: (node: any) => boolean): any | null {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return null;
|
||||
}
|
||||
if (predicate(obj)) {
|
||||
return obj;
|
||||
}
|
||||
for (const value of Object.values(obj)) {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const found = findNode(item, predicate);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
} else if (value && typeof value === 'object') {
|
||||
const found = findNode(value, predicate);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
describe('_checkout_mileage.json - 적용 실패 토스트 메시지 (U15)', () => {
|
||||
// 마일리지 적용 apiCall(PUT /checkout) 노드
|
||||
// (method 는 params.method, target 은 액션 top-level)
|
||||
const applyAction = findNode(
|
||||
mileagePartial,
|
||||
(n) =>
|
||||
n.handler === 'apiCall' &&
|
||||
n.params?.method === 'PUT' &&
|
||||
typeof n.target === 'string' &&
|
||||
n.target.includes('/checkout')
|
||||
);
|
||||
|
||||
it('마일리지 적용 apiCall(PUT /checkout)이 존재한다', () => {
|
||||
expect(applyAction, '마일리지 적용 apiCall 이 없다').toBeTruthy();
|
||||
});
|
||||
|
||||
it('onError 토스트가 error.errors?.message 를 우선 사용한다', () => {
|
||||
const onError = applyAction.onError ?? [];
|
||||
const toast = (Array.isArray(onError) ? onError : [onError]).find(
|
||||
(a: any) => a.handler === 'toast'
|
||||
);
|
||||
|
||||
expect(toast, 'onError 토스트가 없다').toBeTruthy();
|
||||
// 구체 안내(errors.message) 우선, 없으면 상단 generic(message) fallback
|
||||
expect(toast.params.message).toContain('error.errors?.message');
|
||||
expect(toast.params.message).toContain('error.message');
|
||||
});
|
||||
|
||||
it('onError 토스트가 generic message 만 단독 참조하지 않는다 (회귀 가드)', () => {
|
||||
const onError = applyAction.onError ?? [];
|
||||
const toast = (Array.isArray(onError) ? onError : [onError]).find(
|
||||
(a: any) => a.handler === 'toast'
|
||||
);
|
||||
|
||||
// "{{error.message}}" 단독이면 구체 안내가 묻힘 → 금지
|
||||
expect(toast.params.message).not.toBe('{{error.message}}');
|
||||
});
|
||||
});
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
/**
|
||||
* @file order-cancelled-earned-points-hidden.test.tsx
|
||||
* @description U19③ — 취소 주문의 "적립 예정" 마일리지 숨김 회귀 렌더 테스트 (유저 화면 3종)
|
||||
*
|
||||
* 결함: total_earned_points_amount 는 취소 후에도 주문시점 스냅샷으로 양수가 보존된다
|
||||
* (실 적립은 스케줄러가 option_status 기준으로 차단). 레이아웃이 `> 0` 만 검사하면
|
||||
* 취소 주문에도 "적립 예정 +NNN P" 가 계속 노출된다.
|
||||
*
|
||||
* 정정: 노출 블록 if 에 취소/부분취소 제외 가드를 결합한다(값 보존, 표시만 숨김).
|
||||
* order.data: `... > 0 && order.data.order_status !== 'cancelled' && !order.data.is_partially_cancelled`
|
||||
* 목록 iteration order.*: 동일 논리 (order.* 경로)
|
||||
*
|
||||
* 본 테스트는 각 실제 레이아웃에서 적립예정 블록의 if 식을 추출해 그대로 렌더한다.
|
||||
* 가드가 없으면 취소 데이터에서 RED, 가드가 있으면 GREEN.
|
||||
*
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import {
|
||||
createLayoutTest,
|
||||
screen,
|
||||
waitFor,
|
||||
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
|
||||
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
|
||||
import paymentJson from '../../../layouts/partials/mypage/orders/_payment.json';
|
||||
import listJson from '../../../layouts/partials/mypage/orders/_list.json';
|
||||
import orderCompleteJson from '../../../layouts/shop/order_complete.json';
|
||||
|
||||
const TestDiv: React.FC<any> = ({ className, children, 'data-testid': testId }) => (
|
||||
<div className={className} data-testid={testId}>{children}</div>
|
||||
);
|
||||
const TestSpan: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
|
||||
<span className={className} data-testid={testId}>{children || text}</span>
|
||||
);
|
||||
const TestP: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
|
||||
<p className={className} data-testid={testId}>{children || text}</p>
|
||||
);
|
||||
const TestFragment: React.FC<any> = ({ children }) => <>{children}</>;
|
||||
|
||||
function findNode(node: any, predicate: (n: any) => boolean): any {
|
||||
if (node == null || typeof node !== 'object') return null;
|
||||
if (predicate(node)) return node;
|
||||
for (const value of Object.values(node)) {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const hit = findNode(item, predicate);
|
||||
if (hit) return hit;
|
||||
}
|
||||
} else if (value && typeof value === 'object') {
|
||||
const hit = findNode(value, predicate);
|
||||
if (hit) return hit;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 트리에서 total_earned_points_amount 노출 블록의 if 식 추출 */
|
||||
function getEarnedIf(tree: any): string {
|
||||
const node = findNode(
|
||||
tree,
|
||||
(n) => typeof n.if === 'string' && n.if.includes('total_earned_points_amount'),
|
||||
);
|
||||
if (!node) throw new Error('적립예정 블록 if 식을 찾지 못함');
|
||||
return node.if as string;
|
||||
}
|
||||
|
||||
function registerComponents() {
|
||||
const registry = ComponentRegistry.getInstance();
|
||||
(registry as any).registry = {
|
||||
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
|
||||
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
|
||||
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
|
||||
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
|
||||
};
|
||||
}
|
||||
|
||||
// order.data.* 컨텍스트 (주문상세 결제정보) 프로브
|
||||
function buildDetailProbe(earnedIf: string) {
|
||||
return {
|
||||
version: '1.0.0',
|
||||
layout_name: 'test/earned-detail',
|
||||
data_sources: [
|
||||
{ id: 'order', type: 'api', endpoint: '/api/test/order', method: 'GET', auto_fetch: true },
|
||||
],
|
||||
components: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
if: earnedIf,
|
||||
props: { 'data-testid': 'earned-block' },
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Span',
|
||||
props: { 'data-testid': 'earned-text' },
|
||||
text: '+{{order.data.total_earned_points_amount_formatted ?? ""}}',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// 목록 iteration order.* 컨텍스트 프로브
|
||||
function buildListProbe(earnedIf: string) {
|
||||
return {
|
||||
version: '1.0.0',
|
||||
layout_name: 'test/earned-list',
|
||||
data_sources: [
|
||||
{ id: 'orders', type: 'api', endpoint: '/api/test/orders', method: 'GET', auto_fetch: true },
|
||||
],
|
||||
components: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
iteration: { source: '{{orders.data ?? []}}', item_var: 'order' },
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'P',
|
||||
if: earnedIf,
|
||||
props: { 'data-testid': 'earned-text' },
|
||||
text: '+{{order.total_earned_points_amount_formatted ?? ""}}',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const normalDetail = {
|
||||
data: {
|
||||
total_earned_points_amount: 840,
|
||||
total_earned_points_amount_formatted: '840원',
|
||||
order_status: 'confirmed',
|
||||
is_partially_cancelled: false,
|
||||
},
|
||||
};
|
||||
const cancelledDetail = {
|
||||
data: {
|
||||
total_earned_points_amount: 840,
|
||||
total_earned_points_amount_formatted: '840원',
|
||||
order_status: 'cancelled',
|
||||
is_partially_cancelled: false,
|
||||
},
|
||||
};
|
||||
const partialCancelledDetail = {
|
||||
data: {
|
||||
total_earned_points_amount: 840,
|
||||
total_earned_points_amount_formatted: '840원',
|
||||
order_status: 'confirmed',
|
||||
is_partially_cancelled: true,
|
||||
},
|
||||
};
|
||||
|
||||
describe('U19③-a 유저 주문상세 결제정보 적립예정 가드 (_payment.json)', () => {
|
||||
let testUtils: ReturnType<typeof createLayoutTest>;
|
||||
beforeEach(registerComponents);
|
||||
afterEach(() => { if (testUtils) testUtils.cleanup(); vi.clearAllMocks(); });
|
||||
|
||||
it('정상 주문은 적립예정이 노출된다', async () => {
|
||||
testUtils = createLayoutTest(buildDetailProbe(getEarnedIf(paymentJson)));
|
||||
testUtils.mockApi('order', { response: normalDetail });
|
||||
await testUtils.render();
|
||||
await waitFor(() => expect(screen.getByTestId('earned-text')).toHaveTextContent('840원'));
|
||||
});
|
||||
|
||||
it('전체취소 주문은 적립예정이 미노출된다', async () => {
|
||||
testUtils = createLayoutTest(buildDetailProbe(getEarnedIf(paymentJson)));
|
||||
testUtils.mockApi('order', { response: cancelledDetail });
|
||||
await testUtils.render();
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
expect(screen.queryByTestId('earned-block')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('부분취소 주문은 적립예정이 미노출된다', async () => {
|
||||
testUtils = createLayoutTest(buildDetailProbe(getEarnedIf(paymentJson)));
|
||||
testUtils.mockApi('order', { response: partialCancelledDetail });
|
||||
await testUtils.render();
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
expect(screen.queryByTestId('earned-block')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('U19③-b 유저 주문목록 카드 적립예정 가드 (_list.json)', () => {
|
||||
let testUtils: ReturnType<typeof createLayoutTest>;
|
||||
beforeEach(registerComponents);
|
||||
afterEach(() => { if (testUtils) testUtils.cleanup(); vi.clearAllMocks(); });
|
||||
|
||||
// 유저 주문목록은 UserOrderListResource 가 order_status 가 아닌 `status` 키로 노출한다.
|
||||
const listRow = (status: string, partial: boolean) => ({
|
||||
total_earned_points_amount: 840,
|
||||
total_earned_points_amount_formatted: '840원',
|
||||
status,
|
||||
is_partially_cancelled: partial,
|
||||
});
|
||||
|
||||
// 회귀 가드(라이브 검수에서 발견): _list.json 의 취소 가드는 UserOrderListResource 가
|
||||
// 노출하는 실제 필드명 `order.status` 를 써야 한다. `order.order_status`(존재하지 않는 키)를
|
||||
// 쓰면 항상 undefined 라 전체취소가 숨겨지지 않는다.
|
||||
it('_list.json 적립예정 가드는 order.order_status 가 아닌 order.status 를 검사한다', () => {
|
||||
const earnedIf = getEarnedIf(listJson);
|
||||
expect(earnedIf).toContain("order.status !== 'cancelled'");
|
||||
expect(earnedIf).not.toContain('order.order_status');
|
||||
});
|
||||
|
||||
it('정상 주문 카드는 적립예정이 노출된다', async () => {
|
||||
testUtils = createLayoutTest(buildListProbe(getEarnedIf(listJson)));
|
||||
testUtils.mockApi('orders', { response: { data: [listRow('confirmed', false)] } });
|
||||
await testUtils.render();
|
||||
await waitFor(() => expect(screen.getByTestId('earned-text')).toHaveTextContent('840원'));
|
||||
});
|
||||
|
||||
it('전체취소 주문 카드는 적립예정이 미노출된다', async () => {
|
||||
testUtils = createLayoutTest(buildListProbe(getEarnedIf(listJson)));
|
||||
testUtils.mockApi('orders', { response: { data: [listRow('cancelled', false)] } });
|
||||
await testUtils.render();
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
expect(screen.queryByTestId('earned-text')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('부분취소 주문 카드는 적립예정이 미노출된다', async () => {
|
||||
testUtils = createLayoutTest(buildListProbe(getEarnedIf(listJson)));
|
||||
testUtils.mockApi('orders', { response: { data: [listRow('confirmed', true)] } });
|
||||
await testUtils.render();
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
expect(screen.queryByTestId('earned-text')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('U19③-e 주문완료 화면 적립예정 가드 (order_complete.json)', () => {
|
||||
let testUtils: ReturnType<typeof createLayoutTest>;
|
||||
beforeEach(registerComponents);
|
||||
afterEach(() => { if (testUtils) testUtils.cleanup(); vi.clearAllMocks(); });
|
||||
|
||||
// order_complete 는 orderData?.data.* 컨텍스트 — 별도 프로브
|
||||
function buildOrderCompleteProbe(earnedIf: string) {
|
||||
return {
|
||||
version: '1.0.0',
|
||||
layout_name: 'test/earned-complete',
|
||||
data_sources: [
|
||||
{ id: 'orderData', type: 'api', endpoint: '/api/test/order', method: 'GET', auto_fetch: true },
|
||||
],
|
||||
components: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
if: earnedIf,
|
||||
props: { 'data-testid': 'earned-block' },
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Span',
|
||||
props: { 'data-testid': 'earned-text' },
|
||||
text: '+{{orderData?.data?.total_earned_points_amount_formatted ?? ""}}',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
it('정상 결제완료는 적립예정이 노출된다 (회귀 없음)', async () => {
|
||||
testUtils = createLayoutTest(buildOrderCompleteProbe(getEarnedIf(orderCompleteJson)));
|
||||
testUtils.mockApi('orderData', {
|
||||
response: {
|
||||
data: {
|
||||
total_earned_points_amount: 840,
|
||||
total_earned_points_amount_formatted: '840원',
|
||||
order_status: 'paid',
|
||||
is_partially_cancelled: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
await testUtils.render();
|
||||
await waitFor(() => expect(screen.getByTestId('earned-text')).toHaveTextContent('840원'));
|
||||
});
|
||||
|
||||
it('전체취소 상태로 진입해도 적립예정이 미노출된다 (일관성)', async () => {
|
||||
testUtils = createLayoutTest(buildOrderCompleteProbe(getEarnedIf(orderCompleteJson)));
|
||||
testUtils.mockApi('orderData', {
|
||||
response: {
|
||||
data: {
|
||||
total_earned_points_amount: 840,
|
||||
total_earned_points_amount_formatted: '840원',
|
||||
order_status: 'cancelled',
|
||||
is_partially_cancelled: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
await testUtils.render();
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
expect(screen.queryByTestId('earned-block')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* @file order-item-subtotal-display.test.tsx
|
||||
* @description U19② — 무할인 주문 항목의 KRW 소계 표시 회귀 렌더 테스트
|
||||
*
|
||||
* 결함: OrderOption.subtotal_discount_amount 는 모델 decimal:2 캐스트로 JSON 에
|
||||
* 문자열("0.00")로 직렬화된다. _items.json 의 무할인 분기 `if` 가 strict 비교
|
||||
* (`=== 0`)를 쓰면 "0.00" === 0 → false 가 되어, 무할인 항목 소계가 할인/무할인
|
||||
* 양 분기 모두에서 미렌더되어 화면에서 사라진다.
|
||||
*
|
||||
* 정정: OrderOptionResource 가 비교용 숫자 보조 필드 subtotal_discount_amount_value(float)
|
||||
* 를 노출하고, _items.json 의 비교가 이 숫자 필드를 사용하도록 정정한다.
|
||||
*
|
||||
* 본 테스트는 _items.json 실제 파일에서 무할인/할인 분기의 `if` 식을 추출해 그대로
|
||||
* 렌더(템플릿 엔진 ConditionEvaluator 실 평가)하므로, 비교 기준이 문자열 컬럼이면
|
||||
* RED, 숫자 보조 필드면 GREEN 이 된다.
|
||||
*
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import {
|
||||
createLayoutTest,
|
||||
screen,
|
||||
waitFor,
|
||||
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
|
||||
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
|
||||
import itemsJson from '../../../layouts/partials/mypage/orders/_items.json';
|
||||
|
||||
// ---- 테스트 컴포넌트 ----
|
||||
const TestDiv: React.FC<any> = ({ className, children, 'data-testid': testId }) => (
|
||||
<div className={className} data-testid={testId}>{children}</div>
|
||||
);
|
||||
const TestSpan: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
|
||||
<span className={className} data-testid={testId}>{children || text}</span>
|
||||
);
|
||||
const TestFragment: React.FC<any> = ({ children }) => <>{children}</>;
|
||||
|
||||
/** 객체 트리에서 술어를 만족하는 첫 노드를 깊이우선 탐색 */
|
||||
function findNode(node: any, predicate: (n: any) => boolean): any {
|
||||
if (node == null || typeof node !== 'object') return null;
|
||||
if (predicate(node)) return node;
|
||||
for (const value of Object.values(node)) {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const hit = findNode(item, predicate);
|
||||
if (hit) return hit;
|
||||
}
|
||||
} else if (value && typeof value === 'object') {
|
||||
const hit = findNode(value, predicate);
|
||||
if (hit) return hit;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** _items.json 에서 무할인 소계 분기의 실제 if 식을 추출 (line-through 없는 단일 Span) */
|
||||
function getNoDiscountSubtotalIf(): string {
|
||||
const node = findNode(
|
||||
itemsJson,
|
||||
(n) =>
|
||||
typeof n.if === 'string' &&
|
||||
n.if.includes('subtotal_discount_amount') &&
|
||||
n.if.includes('=== 0') &&
|
||||
n.name === 'Span'
|
||||
);
|
||||
if (!node) throw new Error('무할인 소계 분기 if 식을 _items.json 에서 찾지 못함');
|
||||
return node.if as string;
|
||||
}
|
||||
|
||||
/** _items.json 에서 할인 소계 분기(`> 0`)의 실제 if 식을 추출 */
|
||||
function getDiscountSubtotalIf(): string {
|
||||
const node = findNode(
|
||||
itemsJson,
|
||||
(n) =>
|
||||
typeof n.if === 'string' &&
|
||||
n.if.includes('subtotal_discount_amount') &&
|
||||
n.if.includes('> 0') &&
|
||||
n.name === 'Div'
|
||||
);
|
||||
if (!node) throw new Error('할인 소계 분기 if 식을 _items.json 에서 찾지 못함');
|
||||
return node.if as string;
|
||||
}
|
||||
|
||||
// 백엔드 직렬화 재현: decimal:2 컬럼은 문자열, _value 보조 필드는 숫자
|
||||
const noDiscountItem = {
|
||||
id: 1,
|
||||
product_name: '무할인 상품',
|
||||
subtotal_discount_amount: '0.00', // decimal:2 → 문자열
|
||||
subtotal_discount_amount_value: 0, // (float) 보조 필드
|
||||
subtotal_price_formatted: '30,000원',
|
||||
mc_subtotal_price: { KRW: { formatted: '30,000원' } },
|
||||
mc_final_amount: { KRW: { formatted: '30,000원' } },
|
||||
};
|
||||
|
||||
const discountItem = {
|
||||
id: 2,
|
||||
product_name: '할인 상품',
|
||||
subtotal_discount_amount: '3000.00',
|
||||
subtotal_discount_amount_value: 3000,
|
||||
subtotal_price_formatted: '30,000원',
|
||||
mc_subtotal_price: { KRW: { formatted: '30,000원' } },
|
||||
mc_final_amount: { KRW: { formatted: '27,000원' } },
|
||||
};
|
||||
|
||||
function buildProbeLayout(item: any, noDiscountIf: string, discountIf: string) {
|
||||
return {
|
||||
version: '1.0.0',
|
||||
layout_name: 'test/order-item-subtotal',
|
||||
data_sources: [
|
||||
{ id: 'order', type: 'api', endpoint: '/api/test/order', method: 'GET', auto_fetch: true },
|
||||
],
|
||||
components: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
iteration: { source: '{{order.data.options ?? []}}', item_var: 'item' },
|
||||
children: [
|
||||
// 할인 분기 (line-through + final)
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
if: discountIf,
|
||||
props: { 'data-testid': 'discount-block' },
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Span',
|
||||
props: { 'data-testid': 'discount-subtotal' },
|
||||
text: '{{item.mc_final_amount?.KRW?.formatted ?? ""}}',
|
||||
},
|
||||
],
|
||||
},
|
||||
// 무할인 분기 (단일 소계 Span)
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Span',
|
||||
if: noDiscountIf,
|
||||
props: { 'data-testid': 'no-discount-subtotal' },
|
||||
text: '{{item.mc_subtotal_price?.KRW?.formatted ?? item.subtotal_price_formatted ?? ""}}',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe('U19② 무할인 주문 항목 소계 표시 (_items.json if 식 실 평가)', () => {
|
||||
let testUtils: ReturnType<typeof createLayoutTest>;
|
||||
|
||||
beforeEach(() => {
|
||||
const registry = ComponentRegistry.getInstance();
|
||||
(registry as any).registry = {
|
||||
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
|
||||
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
|
||||
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (testUtils) testUtils.cleanup();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('무할인 항목의 소계 Span 이 렌더된다 (decimal 문자열 strict 비교 회귀 차단)', async () => {
|
||||
const layout = buildProbeLayout(noDiscountItem, getNoDiscountSubtotalIf(), getDiscountSubtotalIf());
|
||||
testUtils = createLayoutTest(layout);
|
||||
testUtils.mockApi('order', { response: { data: { options: [noDiscountItem] } } });
|
||||
await testUtils.render();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('no-discount-subtotal')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('no-discount-subtotal')).toHaveTextContent('30,000원');
|
||||
});
|
||||
// 무할인이므로 할인 분기는 미렌더
|
||||
expect(screen.queryByTestId('discount-block')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('할인 항목은 할인 분기가 렌더되고 무할인 분기는 미렌더된다 (회귀 없음)', async () => {
|
||||
const layout = buildProbeLayout(discountItem, getNoDiscountSubtotalIf(), getDiscountSubtotalIf());
|
||||
testUtils = createLayoutTest(layout);
|
||||
testUtils.mockApi('order', { response: { data: { options: [discountItem] } } });
|
||||
await testUtils.render();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('discount-subtotal')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('discount-subtotal')).toHaveTextContent('27,000원');
|
||||
});
|
||||
expect(screen.queryByTestId('no-discount-subtotal')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('비회원 주문상세도 동일 partial 공유로 무할인 소계가 렌더된다 (GuestOrderResource shape)', async () => {
|
||||
// GuestOrderResource 는 OrderOptionResource::collection 을 그대로 노출하므로
|
||||
// subtotal_discount_amount_value 보조 필드를 회원과 동일하게 가진다.
|
||||
const guestNoDiscountItem = { ...noDiscountItem, id: 99 };
|
||||
const layout = buildProbeLayout(
|
||||
guestNoDiscountItem,
|
||||
getNoDiscountSubtotalIf(),
|
||||
getDiscountSubtotalIf(),
|
||||
);
|
||||
testUtils = createLayoutTest(layout);
|
||||
testUtils.mockApi('order', { response: { data: { options: [guestNoDiscountItem] } } });
|
||||
await testUtils.render();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('no-discount-subtotal')).toHaveTextContent('30,000원');
|
||||
});
|
||||
});
|
||||
});
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* @file shop-buy-now-direct-checkout.test.tsx
|
||||
* @description 상품 상세 "바로 구매" 장바구니 미경유 검증 (직접 항목 체크아웃)
|
||||
*
|
||||
* 배경: "바로 구매"가 먼저 POST /cart 로 장바구니에 담은 뒤 체크아웃해, 장바구니 기존
|
||||
* 동일 상품 수량과 합산되어 한도 초과 차단되거나 장바구니가 오염되던 결함.
|
||||
* direct_items 로 장바구니를 경유하지 않고 바로 체크아웃하도록 변경.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import purchaseCard from '../../../layouts/partials/shop/detail/_purchase_card.json';
|
||||
|
||||
/**
|
||||
* JSON 트리에서 조건을 만족하는 모든 노드를 수집한다.
|
||||
*/
|
||||
function collectNodes(obj: any, predicate: (node: any) => boolean, acc: any[] = []): any[] {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return acc;
|
||||
}
|
||||
if (predicate(obj)) {
|
||||
acc.push(obj);
|
||||
}
|
||||
for (const value of Object.values(obj)) {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item) => collectNodes(item, predicate, acc));
|
||||
} else if (value && typeof value === 'object') {
|
||||
collectNodes(value, predicate, acc);
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
describe('_purchase_card.json - 바로 구매 장바구니 미경유', () => {
|
||||
// "바로 구매" 버튼 노드 (text = $t:shop.product.buy_now 자식 Span 보유) 의 액션 서브트리만 검사
|
||||
const buyNowButton = collectNodes(
|
||||
purchaseCard,
|
||||
(n) =>
|
||||
n.name === 'Button' &&
|
||||
Array.isArray(n.actions) &&
|
||||
JSON.stringify(n.children ?? []).includes('shop.product.buy_now')
|
||||
)[0];
|
||||
|
||||
const buyNowApiCalls = buyNowButton
|
||||
? collectNodes(buyNowButton.actions, (n) => n.handler === 'apiCall')
|
||||
: [];
|
||||
|
||||
it('바로 구매 버튼이 존재한다', () => {
|
||||
expect(buyNowButton, '바로 구매 버튼을 찾지 못함').toBeTruthy();
|
||||
});
|
||||
|
||||
it('바로 구매 흐름이 체크아웃을 호출한다', () => {
|
||||
const hasCheckout = buyNowApiCalls.some(
|
||||
(n) => typeof n.target === 'string' && n.target.includes('/checkout')
|
||||
);
|
||||
expect(hasCheckout).toBe(true);
|
||||
});
|
||||
|
||||
it('바로 구매 흐름이 장바구니 담기(POST /cart)를 거치지 않는다 (회귀 가드)', () => {
|
||||
const cartPosts = buyNowApiCalls.filter(
|
||||
(n) =>
|
||||
typeof n.target === 'string' &&
|
||||
/\/cart($|[^a-z])/.test(n.target) &&
|
||||
n.params?.method === 'POST'
|
||||
);
|
||||
expect(cartPosts.length).toBe(0);
|
||||
});
|
||||
|
||||
it('바로 구매 체크아웃 body 가 direct_items 를 전달한다', () => {
|
||||
const usesDirectItems = buyNowApiCalls.some((n) => {
|
||||
const body = n.params?.body;
|
||||
return (
|
||||
typeof n.target === 'string' &&
|
||||
n.target.includes('/checkout') &&
|
||||
typeof body === 'string' &&
|
||||
body.includes('direct_items')
|
||||
);
|
||||
});
|
||||
expect(usesDirectItems).toBe(true);
|
||||
});
|
||||
});
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* @file shop-cart-unavailable-message.test.tsx
|
||||
* @description 상품 상세 담기/바로구매 실패 토스트 메시지 바인딩 검증 (U13②/U4/A25 후속)
|
||||
*
|
||||
* 배경: 판매중지·구매수량 한도 초과 담기 시 백엔드는 422 + errors.message(구체 안내)를
|
||||
* 내려보내는데, 상품 상세의 담기/바로구매 onError 토스트가 상단 generic message 만 노출해
|
||||
* "구매할 수 없는 상품이 있습니다"만 보이던 결함. error.errors?.message 우선 fallback 으로 정정.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import detailPurchaseCard from '../../../layouts/partials/shop/detail/_purchase_card.json';
|
||||
import optionPurchaseCard from '../../../layouts/partials/shop/_product_purchase_card.json';
|
||||
|
||||
/**
|
||||
* JSON 트리에서 조건을 만족하는 모든 노드를 수집한다.
|
||||
*/
|
||||
function collectNodes(obj: any, predicate: (node: any) => boolean, acc: any[] = []): any[] {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return acc;
|
||||
}
|
||||
if (predicate(obj)) {
|
||||
acc.push(obj);
|
||||
}
|
||||
for (const value of Object.values(obj)) {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item) => collectNodes(item, predicate, acc));
|
||||
} else if (value && typeof value === 'object') {
|
||||
collectNodes(value, predicate, acc);
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃의 모든 error 토스트(handler=toast, type=error, message 가 error 바인딩) 수집.
|
||||
*/
|
||||
function errorToasts(layout: any): any[] {
|
||||
return collectNodes(
|
||||
layout,
|
||||
(n) =>
|
||||
n.handler === 'toast' &&
|
||||
n.params?.type === 'error' &&
|
||||
typeof n.params?.message === 'string' &&
|
||||
n.params.message.includes('error')
|
||||
);
|
||||
}
|
||||
|
||||
describe('상품 상세 담기/바로구매 실패 토스트 (U13②/U4/A25)', () => {
|
||||
const detailToasts = errorToasts(detailPurchaseCard);
|
||||
const optionToasts = errorToasts(optionPurchaseCard);
|
||||
|
||||
it('상세 구매 카드에 error 토스트가 존재한다', () => {
|
||||
expect(detailToasts.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('옵션 상품 카드에 error 토스트가 존재한다', () => {
|
||||
expect(optionToasts.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('모든 error 토스트가 error.errors?.message 를 우선 사용한다 (구체 안내)', () => {
|
||||
[...detailToasts, ...optionToasts].forEach((toast) => {
|
||||
expect(toast.params.message).toContain('error.errors?.message');
|
||||
expect(toast.params.message).toContain('error.message');
|
||||
});
|
||||
});
|
||||
|
||||
it('error 토스트가 generic message 만 단독 참조하지 않는다 (회귀 가드)', () => {
|
||||
[...detailToasts, ...optionToasts].forEach((toast) => {
|
||||
expect(toast.params.message).not.toBe('{{error.message}}');
|
||||
});
|
||||
});
|
||||
});
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* @file shop-cart-unavailable-modal.test.tsx
|
||||
* @description 장바구니 구매불가 모달 reason별 사유 표시 검증 (U13②/U4/A25 후속)
|
||||
*
|
||||
* 배경: 모달이 stock/status reason 만 사유 줄을 그려, A25 로 도입한 max_qty/min_qty 와
|
||||
* 구매대상제한(restricted) 항목은 상품명만 보이고 "왜 구매 불가인지"가 누락되던 결함.
|
||||
* 모든 reason 에 대응 표시 분기를 추가.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import modal from '../../../layouts/partials/shop/_modal_cart_unavailable.json';
|
||||
|
||||
/**
|
||||
* JSON 트리에서 조건을 만족하는 모든 노드를 수집한다.
|
||||
*/
|
||||
function collectNodes(obj: any, predicate: (node: any) => boolean, acc: any[] = []): any[] {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return acc;
|
||||
}
|
||||
if (predicate(obj)) {
|
||||
acc.push(obj);
|
||||
}
|
||||
for (const value of Object.values(obj)) {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item) => collectNodes(item, predicate, acc));
|
||||
} else if (value && typeof value === 'object') {
|
||||
collectNodes(value, predicate, acc);
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
describe('_modal_cart_unavailable.json - reason별 사유 표시 (A25)', () => {
|
||||
// if 조건이 unavailableItem.reason 을 분기하는 노드들
|
||||
const reasonNodes = collectNodes(
|
||||
modal,
|
||||
(n) => typeof n.if === 'string' && n.if.includes('unavailableItem.reason')
|
||||
);
|
||||
|
||||
const ifConditions = reasonNodes.map((n) => n.if as string).join(' || ');
|
||||
|
||||
it.each([['stock'], ['status'], ['max_qty'], ['min_qty'], ['restricted']])(
|
||||
"reason '%s' 에 대한 표시 분기가 존재한다",
|
||||
(reason) => {
|
||||
expect(ifConditions).toContain(`'${reason}'`);
|
||||
}
|
||||
);
|
||||
|
||||
it('max_qty/min_qty 표시는 limit/requested 를 치환한다', () => {
|
||||
const maxNode = reasonNodes.find((n) => (n.if as string).includes("'max_qty'"));
|
||||
const minNode = reasonNodes.find((n) => (n.if as string).includes("'min_qty'"));
|
||||
|
||||
expect(maxNode?.text).toContain('limit=');
|
||||
expect(maxNode?.text).toContain('requested=');
|
||||
expect(minNode?.text).toContain('limit=');
|
||||
});
|
||||
});
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* @file shop-purchase-quantity-limit.test.tsx
|
||||
* @description 옵션 상품 구매수량 한도 UI 바인딩 검증 (A25 / MP05)
|
||||
*
|
||||
* 검증 항목:
|
||||
* 1. 옵션 라인 QuantitySelector max 가 상품 max_purchase_qty 로 clamp 된다
|
||||
* (max>0 시 Math.min(item.stock, max_purchase_qty), max=0 시 item.stock).
|
||||
* 2. 구매/장바구니 버튼 disabled 가 선택 합계 min 미달 / max 초과 시 비활성화된다.
|
||||
* 3. 한도 위반 안내 Span(min/max notice)이 존재한다.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import purchaseCard from '../../../layouts/partials/shop/_product_purchase_card.json';
|
||||
|
||||
/**
|
||||
* JSON 트리에서 조건을 만족하는 첫 노드를 재귀 탐색한다.
|
||||
*/
|
||||
function findNode(obj: any, predicate: (node: any) => boolean): any | null {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return null;
|
||||
}
|
||||
if (predicate(obj)) {
|
||||
return obj;
|
||||
}
|
||||
for (const value of Object.values(obj)) {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const found = findNode(item, predicate);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
} else if (value && typeof value === 'object') {
|
||||
const found = findNode(value, predicate);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 트리에서 조건을 만족하는 모든 노드를 수집한다.
|
||||
*/
|
||||
function collectNodes(obj: any, predicate: (node: any) => boolean, acc: any[] = []): any[] {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return acc;
|
||||
}
|
||||
if (predicate(obj)) {
|
||||
acc.push(obj);
|
||||
}
|
||||
for (const value of Object.values(obj)) {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item) => collectNodes(item, predicate, acc));
|
||||
} else if (value && typeof value === 'object') {
|
||||
collectNodes(value, predicate, acc);
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
describe('_product_purchase_card.json - 옵션 라인 max clamp (A25)', () => {
|
||||
it('QuantitySelector 의 max 가 상품 max_purchase_qty 로 clamp 된다', () => {
|
||||
const selector = findNode(
|
||||
purchaseCard,
|
||||
(n) => n.name === 'QuantitySelector'
|
||||
);
|
||||
|
||||
expect(selector, 'QuantitySelector 노드가 없다').toBeTruthy();
|
||||
|
||||
const max = selector.props?.max ?? '';
|
||||
// max>0 시 Math.min(item.stock, max_purchase_qty), max=0 시 item.stock
|
||||
expect(max).toContain('max_purchase_qty');
|
||||
expect(max).toContain('Math.min(item.stock');
|
||||
expect(max).toContain('item.stock');
|
||||
});
|
||||
});
|
||||
|
||||
describe('_product_purchase_card.json - 합계 버튼 한도 차단 (A25)', () => {
|
||||
const buttons = collectNodes(
|
||||
purchaseCard,
|
||||
(n) => n.name === 'Button' && typeof n.props?.disabled === 'string'
|
||||
);
|
||||
|
||||
it('구매/장바구니 버튼이 2개 이상 존재한다', () => {
|
||||
expect(buttons.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('모든 구매 버튼 disabled 가 min 미달 / max 초과 합계 검증을 포함한다', () => {
|
||||
buttons.forEach((btn) => {
|
||||
const disabled = btn.props.disabled as string;
|
||||
expect(disabled).toContain('min_purchase_qty');
|
||||
expect(disabled).toContain('max_purchase_qty');
|
||||
expect(disabled).toContain('reduce');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('_product_purchase_card.json - 한도 위반 안내 문구 (A25)', () => {
|
||||
it('min/max 구매수량 안내 Span 이 존재한다', () => {
|
||||
const minNotice = findNode(
|
||||
purchaseCard,
|
||||
(n) => typeof n.text === 'string' && n.text.includes('min_purchase_qty_notice')
|
||||
);
|
||||
const maxNotice = findNode(
|
||||
purchaseCard,
|
||||
(n) => typeof n.text === 'string' && n.text.includes('max_purchase_qty_notice')
|
||||
);
|
||||
|
||||
expect(minNotice, 'min_purchase_qty_notice 안내가 없다').toBeTruthy();
|
||||
expect(maxNotice, 'max_purchase_qty_notice 안내가 없다').toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* shop-soldout-computed.test.ts — 상품상세 옵션 품절 표시 (computed 인라인 방식)
|
||||
*
|
||||
* MP07 §2: 재고 없는 옵션을 옵션 드롭다운에서 "(품절)" 비활성으로 표시한다. $call 헬퍼
|
||||
* 없이, show.json 의 `computed.optionChoices`(순수 인라인 배열식)가 백엔드 is_sold_out
|
||||
* 플래그(ProductOptionResource)를 읽어 그룹별 선택지를 만들고, _purchase_card.json 의
|
||||
* 옵션 select 가 `$computed.optionChoices?.[groupIndex]` 로 참조한다.
|
||||
*
|
||||
* 본 테스트는 (1) show.json 의 computed 표현식 정본을 실제 DataBindingEngine 으로 평가해
|
||||
* 품절 판정(보수적: 호환 조합 전부 품절일 때만 disabled)이 맞는지, (2) _purchase_card.json
|
||||
* 의 select options 표현식이 $computed.optionChoices 를 참조해 그 결과를 펼치는지 — 를
|
||||
* 실제 표현식으로 검증한다(레이아웃 JSON 정본과 동일 문자열 사용 — 회귀 가드).
|
||||
*
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { DataBindingEngine } from '@/core/template-engine/DataBindingEngine';
|
||||
import showLayout from '../../../layouts/shop/show.json';
|
||||
import purchaseCard from '../../../layouts/partials/shop/detail/_purchase_card.json';
|
||||
|
||||
// 레이아웃 정본에서 표현식을 직접 추출 — 정본이 바뀌면 테스트도 따라가 회귀를 잡는다.
|
||||
const COMPUTED_EXPR: string = (showLayout as any).computed.optionChoices.replace(/^\{\{|\}\}$/g, '');
|
||||
|
||||
// _purchase_card.json 의 옵션 select options 표현식 (iteration 안의 Select)
|
||||
function findOptionsExpr(node: any): string | null {
|
||||
if (node && typeof node === 'object') {
|
||||
if (node.name === 'Select' && node.props?.options) return node.props.options;
|
||||
for (const k of Object.keys(node)) {
|
||||
const v = (node as any)[k];
|
||||
if (Array.isArray(v)) {
|
||||
for (const c of v) {
|
||||
const r = findOptionsExpr(c);
|
||||
if (r) return r;
|
||||
}
|
||||
} else if (v && typeof v === 'object') {
|
||||
const r = findOptionsExpr(v);
|
||||
if (r) return r;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const OPTIONS_EXPR: string = (findOptionsExpr(purchaseCard) ?? '').replace(/^\{\{|\}\}$/g, '');
|
||||
|
||||
const colorGroup = { name_localized: '색상', values_localized: ['빨강', '파랑'] };
|
||||
const sizeGroup = { name_localized: '사이즈', values_localized: ['S', 'L'] };
|
||||
|
||||
function opt(localized: Record<string, string>, soldOut: boolean): any {
|
||||
return {
|
||||
option_values_localized: localized,
|
||||
stock_quantity: soldOut ? 0 : 10,
|
||||
is_active: true,
|
||||
is_sold_out: soldOut,
|
||||
};
|
||||
}
|
||||
|
||||
describe('상품상세 옵션 품절 표시 — computed 인라인 방식', () => {
|
||||
let engine: DataBindingEngine;
|
||||
beforeEach(() => {
|
||||
engine = new DataBindingEngine();
|
||||
});
|
||||
|
||||
function evalComputed(option_groups: any[], options: any[], currentSelection: Record<string, string> = {}) {
|
||||
return engine.evaluateExpression(COMPUTED_EXPR, {
|
||||
product: { data: { option_groups, options } },
|
||||
_local: { currentSelection },
|
||||
} as any) as any[];
|
||||
}
|
||||
|
||||
it('show.json computed: 단일 그룹 — 재고0 옵션 값이 disabled + "(품절)" 라벨', () => {
|
||||
const choices = evalComputed([colorGroup], [
|
||||
opt({ 색상: '빨강' }, false),
|
||||
opt({ 색상: '파랑' }, true),
|
||||
]);
|
||||
// choices[0] = 색상 그룹 선택지
|
||||
const red = choices[0].find((c: any) => c.value === '빨강');
|
||||
const blue = choices[0].find((c: any) => c.value === '파랑');
|
||||
expect(red.disabled).toBe(false);
|
||||
expect(blue.disabled).toBe(true);
|
||||
// 품절 값은 라벨에 접미가 붙는다(원본 값보다 길다). 테스트 환경엔 $t 사전이 없어
|
||||
// sold_out_suffix 키가 그대로 반환되므로 "품절" 문자열 자체가 아니라 접미 부착을 검증한다.
|
||||
expect(blue.label).not.toBe('파랑');
|
||||
expect(blue.label.startsWith('파랑 ')).toBe(true);
|
||||
expect(red.label).toBe('빨강'); // 정상 값은 접미 없음
|
||||
});
|
||||
|
||||
it('show.json computed: 다중 그룹 보수적 판정 — 일부만 품절이면 선택 가능, 전부 품절이면 비활성', () => {
|
||||
// 빨강-S(품절) 빨강-L(정상) 파랑-S(품절) 파랑-L(품절)
|
||||
const options = [
|
||||
opt({ 색상: '빨강', 사이즈: 'S' }, true),
|
||||
opt({ 색상: '빨강', 사이즈: 'L' }, false),
|
||||
opt({ 색상: '파랑', 사이즈: 'S' }, true),
|
||||
opt({ 색상: '파랑', 사이즈: 'L' }, true),
|
||||
];
|
||||
const choices = evalComputed([colorGroup, sizeGroup], options);
|
||||
const colorChoices = choices[0];
|
||||
expect(colorChoices.find((c: any) => c.value === '빨강').disabled).toBe(false); // 빨강-L 정상
|
||||
expect(colorChoices.find((c: any) => c.value === '파랑').disabled).toBe(true); // 파랑 전부 품절
|
||||
});
|
||||
|
||||
it('show.json computed: 하위 그룹 — 상위 선택(빨강) 호환 조합 기준 S 품절/L 정상', () => {
|
||||
const options = [
|
||||
opt({ 색상: '빨강', 사이즈: 'S' }, true),
|
||||
opt({ 색상: '빨강', 사이즈: 'L' }, false),
|
||||
opt({ 색상: '파랑', 사이즈: 'S' }, false),
|
||||
opt({ 색상: '파랑', 사이즈: 'L' }, false),
|
||||
];
|
||||
const choices = evalComputed([colorGroup, sizeGroup], options, { 색상: '빨강' });
|
||||
const sizeChoices = choices[1];
|
||||
expect(sizeChoices.find((c: any) => c.value === 'S').disabled).toBe(true);
|
||||
expect(sizeChoices.find((c: any) => c.value === 'L').disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('_purchase_card.json select options: $computed.optionChoices 를 참조해 품절 결과를 펼친다', () => {
|
||||
// computed 결과를 미리 만들어 $computed 로 주입
|
||||
const optionChoices = evalComputed([colorGroup], [
|
||||
opt({ 색상: '빨강' }, false),
|
||||
opt({ 색상: '파랑' }, true),
|
||||
]);
|
||||
const result = engine.evaluateExpression(OPTIONS_EXPR, {
|
||||
group: colorGroup,
|
||||
groupIndex: 0,
|
||||
product: { data: { option_groups: [colorGroup] } },
|
||||
_local: { currentSelection: {} },
|
||||
_computed: { optionChoices },
|
||||
} as any) as any[];
|
||||
// [0]=placeholder, 이후 색상 선택지(품절 반영)
|
||||
expect(result[0].value).toBe('');
|
||||
expect(result.find((c) => c.value === '파랑')?.disabled).toBe(true);
|
||||
expect(result.find((c) => c.value === '빨강')?.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('_purchase_card.json select options: computed 부재 시 평문 폴백(품절 표시 없이 깨지지 않음)', () => {
|
||||
const result = engine.evaluateExpression(OPTIONS_EXPR, {
|
||||
group: colorGroup,
|
||||
groupIndex: 0,
|
||||
product: { data: { option_groups: [colorGroup] } },
|
||||
_local: { currentSelection: {} },
|
||||
_computed: {},
|
||||
} as any) as any[];
|
||||
expect(result.find((c) => c.value === '빨강')).toBeDefined();
|
||||
expect(result.find((c) => c.value === '빨강')?.disabled).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
/**
|
||||
* @file shopAdditionalOptions.test.tsx
|
||||
* @description 상품 추가옵션(유료 옵션) 유저 흐름 레이아웃 검증
|
||||
*
|
||||
* 1. 렌더링: 추가옵션 그룹별 선택지 표시(추가금 라벨) — 최소 레이아웃 실제 렌더
|
||||
* 2. 구조: 실제 partial(_purchase_card / _cart_item / _modal_cart_option_change /
|
||||
* 표시 4화면)이 추가옵션 바인딩·핸들러·필수 가드를 포함하는지 검증
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
|
||||
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
|
||||
|
||||
import purchaseCard from '../../../layouts/partials/shop/detail/_purchase_card.json';
|
||||
import cartItem from '../../../layouts/partials/shop/_cart_item.json';
|
||||
import modalOptionChange from '../../../layouts/partials/shop/_modal_cart_option_change.json';
|
||||
import checkoutItems from '../../../layouts/partials/shop/_checkout_items.json';
|
||||
import orderComplete from '../../../layouts/shop/order_complete.json';
|
||||
import mypageItems from '../../../layouts/partials/mypage/orders/_items.json';
|
||||
|
||||
// ============================================================
|
||||
// 테스트용 컴포넌트
|
||||
// ============================================================
|
||||
|
||||
const TestDiv: React.FC<any> = ({ className, children, 'data-testid': testId }) => (
|
||||
<div className={className} data-testid={testId}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
const TestSpan: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
|
||||
<span className={className} data-testid={testId}>
|
||||
{children ?? text}
|
||||
</span>
|
||||
);
|
||||
const TestP: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
|
||||
<p className={className} data-testid={testId}>
|
||||
{children ?? text}
|
||||
</p>
|
||||
);
|
||||
|
||||
function setupRegistry(): ComponentRegistry {
|
||||
const registry = ComponentRegistry.getInstance();
|
||||
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
|
||||
(registry as any).registry = {
|
||||
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
|
||||
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
|
||||
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
|
||||
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
|
||||
};
|
||||
return registry;
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 1. 렌더링 — 추가옵션 라인 표시 (장바구니 항목 스타일)
|
||||
// ============================================================
|
||||
|
||||
describe('추가옵션 표시 렌더링', () => {
|
||||
beforeEach(() => setupRegistry());
|
||||
|
||||
const layout = {
|
||||
version: '1.0.0',
|
||||
layout_name: 'shop_additional_options_test',
|
||||
data_sources: [
|
||||
{ id: 'cart', type: 'api', endpoint: '/api/cart', method: 'GET', auto_fetch: true },
|
||||
],
|
||||
components: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
iteration: { source: '{{cart.data.items ?? []}}', item_var: 'item' },
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'Div',
|
||||
if: '{{item.additional_options?.length > 0}}',
|
||||
iteration: { source: '{{item.additional_options ?? []}}', item_var: 'addOpt' },
|
||||
children: [
|
||||
{
|
||||
type: 'basic',
|
||||
name: 'P',
|
||||
text: "{{addOpt.group_name}}: {{addOpt.name}}{{(addOpt.price_adjustment ?? 0) > 0 ? ' (+' + addOpt.price_adjustment.toLocaleString() + '원)' : ''}}",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it('선택된 추가옵션 그룹명·선택지명·추가금을 표시한다', async () => {
|
||||
const testUtils = createLayoutTest(layout as any);
|
||||
testUtils.mockApi('cart', {
|
||||
response: {
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
additional_options: [
|
||||
{ additional_option_id: 1, value_id: 101, group_name: '각인', name: '각인 추가', price_adjustment: 5000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
await testUtils.render();
|
||||
|
||||
expect(
|
||||
screen.getByText((c) => c.includes('각인 추가') && c.includes('5,000'))
|
||||
).toBeInTheDocument();
|
||||
testUtils.cleanup();
|
||||
});
|
||||
|
||||
it('추가금 0인 선택지는 추가금 표기를 생략한다', async () => {
|
||||
const testUtils = createLayoutTest(layout as any);
|
||||
testUtils.mockApi('cart', {
|
||||
response: {
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
additional_options: [
|
||||
{ additional_option_id: 1, value_id: 100, group_name: '각인', name: '없음', price_adjustment: 0 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const { container } = await testUtils.render();
|
||||
|
||||
expect(
|
||||
screen.getByText((c) => c.includes('각인') && c.includes('없음'))
|
||||
).toBeInTheDocument();
|
||||
// 추가금 0 → '+' 표기 없음
|
||||
expect(container.textContent).not.toContain('+0');
|
||||
testUtils.cleanup();
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// 2. 구조 검증 — 실제 partial
|
||||
// ============================================================
|
||||
|
||||
describe('_purchase_card.json 구조 — 블럭별 추가옵션', () => {
|
||||
const str = JSON.stringify(purchaseCard);
|
||||
|
||||
it('블럭 내부 추가옵션 그룹 iteration이 product.data.additional_options를 사용한다', () => {
|
||||
expect(str).toContain('product.data?.additional_options');
|
||||
expect(str).toContain('"item_var":"addGroup"');
|
||||
});
|
||||
|
||||
it('블럭별 추가옵션 변경 핸들러 setBlockAdditionalOption을 호출한다', () => {
|
||||
expect(str).toContain('sirsoft-basic.setBlockAdditionalOption');
|
||||
});
|
||||
|
||||
it('addSelectedItemIfComplete에 additionalOptionGroups를 전달한다', () => {
|
||||
expect(str).toContain('"additionalOptionGroups"');
|
||||
});
|
||||
|
||||
it('담기/구매 body에 additional_option_selections를 포함한다', () => {
|
||||
expect(str).toContain('additional_option_selections');
|
||||
expect(str).toContain('additional_option_id');
|
||||
expect(str).toContain('value_id');
|
||||
});
|
||||
|
||||
it('필수 추가옵션 미선택 차단 가드(additional_option_required)가 있다', () => {
|
||||
expect(str).toContain('shop.additional_option_required');
|
||||
expect(str).toContain('is_required');
|
||||
});
|
||||
|
||||
it('레거시 카드레벨 자유텍스트 추가옵션 입력을 제거했다', () => {
|
||||
// 구 스텁: additional_option_{{addOption.id}} 텍스트 input
|
||||
expect(str).not.toContain('additional_option_{{addOption.id}}');
|
||||
expect(str).not.toContain('_local.additionalOptions?.[addOption.id]');
|
||||
});
|
||||
|
||||
it('선택된 옵션 블록은 space-y-4 부모 + iteration 자식으로 분리한다 (붙어 보이는 회귀 방지)', () => {
|
||||
// G7 엔진은 iteration 노드를 N번 복제하므로, space-y-* 가 iteration 과 같은 노드에 있으면
|
||||
// 각 아이템이 자기 wrapper 를 소유해 형제 간 간격이 0 이 된다. 따라서:
|
||||
// - selectedOptionItems iteration 노드 자체에는 space-y-* 가 없어야 한다
|
||||
// - 그 iteration 노드의 부모가 space-y-4 를 가져야 한다
|
||||
const findParentOfSelectedIteration = (
|
||||
node: any,
|
||||
parent: any
|
||||
): { iterNode: any; parent: any } | null => {
|
||||
if (!node || typeof node !== 'object') return null;
|
||||
const src = node.iteration?.source;
|
||||
if (typeof src === 'string' && src.includes('_local.selectedOptionItems')) {
|
||||
return { iterNode: node, parent };
|
||||
}
|
||||
for (const child of node.children ?? []) {
|
||||
const found = findParentOfSelectedIteration(child, node);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
let result: { iterNode: any; parent: any } | null = null;
|
||||
for (const child of (purchaseCard as any).children ?? []) {
|
||||
result = findParentOfSelectedIteration(child, purchaseCard);
|
||||
if (result) break;
|
||||
}
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
const iterClass = result!.iterNode.props?.className ?? '';
|
||||
const parentClass = result!.parent?.props?.className ?? '';
|
||||
// iteration 노드에는 space-y-* 금지 (동거 시 간격 미적용 회귀)
|
||||
expect(iterClass).not.toMatch(/\bspace-y-/);
|
||||
// 부모가 형제 간격(space-y-4)을 담당
|
||||
expect(parentClass).toContain('space-y-4');
|
||||
});
|
||||
});
|
||||
|
||||
describe('_cart_item.json 구조 — 추가옵션 표시 + 모달 시드', () => {
|
||||
const str = JSON.stringify(cartItem);
|
||||
|
||||
it('item.additional_options를 옵션 라인 아래 표시한다', () => {
|
||||
expect(str).toContain('item.additional_options');
|
||||
expect(str).toContain('addOpt.group_name');
|
||||
});
|
||||
|
||||
it('옵션변경 모달 열기 시 additionalSelections를 현재 선택으로 시드한다', () => {
|
||||
expect(str).toContain('additionalSelections');
|
||||
expect(str).toContain('a.additional_option_id');
|
||||
expect(str).toContain('a.value_id');
|
||||
});
|
||||
});
|
||||
|
||||
describe('_modal_cart_option_change.json 구조 — 추가옵션 재선택', () => {
|
||||
const str = JSON.stringify(modalOptionChange);
|
||||
|
||||
it('optionProduct.additional_options 기반 그룹 재선택 UI가 있다', () => {
|
||||
expect(str).toContain('optionProduct?.additional_options');
|
||||
expect(str).toContain('additionalSelections');
|
||||
});
|
||||
|
||||
it('PATCH body에 additional_option_selections를 포함한다', () => {
|
||||
expect(str).toContain('additional_option_selections');
|
||||
});
|
||||
});
|
||||
|
||||
describe('표시 전용 화면 — 스냅샷 기반 추가옵션 별행', () => {
|
||||
it('체크아웃 항목에 additional_options 표시가 있다', () => {
|
||||
expect(JSON.stringify(checkoutItems)).toContain('item.additional_options');
|
||||
});
|
||||
it('주문완료 항목에 additional_options 표시가 있다', () => {
|
||||
expect(JSON.stringify(orderComplete)).toContain('item.additional_options');
|
||||
});
|
||||
it('마이페이지 주문상세 항목에 additional_options 표시가 있다', () => {
|
||||
expect(JSON.stringify(mypageItems)).toContain('item.additional_options');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user