v7.0.0-beta.1 release

This commit is contained in:
HeuJung committed 2026-04-01 10:30:52 +09:00
commit 6595fd0eb5
3967 files changed
+1875383

No files matched your search

@@ -0,0 +1,21 @@
import React from 'react';
export interface AProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {}
/**
* 기본 a(링크) 컴포넌트
*/
export const A: React.FC<AProps> = ({
children,
className = '',
...props
}) => {
return (
<a
className={className}
{...props}
>
{children}
</a>
);
};
@@ -0,0 +1,38 @@
import React, { forwardRef } from 'react';
// G7Core 전역 객체의 스타일 헬퍼 접근
const G7Core = () => (window as any).G7Core;
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'danger' | 'success';
size?: 'sm' | 'md' | 'lg';
}
/**
* 기본 버튼 컴포넌트
*/
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(({
children,
variant = 'primary',
size = 'md',
className = '',
...props
}, ref) => {
const baseClasses = 'inline-flex items-center justify-center';
// G7Core.style.mergeClasses를 사용하여 충돌하는 Tailwind 클래스 병합
const mergedClassName = G7Core()?.style?.mergeClasses?.(baseClasses, className)
?? `${baseClasses} ${className}`;
return (
<button
ref={ref}
className={mergedClassName}
{...props}
>
{children}
</button>
);
});
Button.displayName = 'Button';
@@ -0,0 +1,52 @@
import React, { forwardRef, useEffect, useRef } from 'react';
export interface CheckboxProps extends React.InputHTMLAttributes<HTMLInputElement> {
label?: string;
/**
* indeterminate 상태 (부분 선택 상태)
*
* 부모-자식 체크박스 연동에서 일부 자식만 선택되었을 때 사용합니다.
* HTML checkbox의 indeterminate 속성을 JavaScript로 설정합니다.
*/
indeterminate?: boolean;
}
/**
* 기본 체크박스 컴포넌트
*
* forwardRef를 사용하여 ref 전달을 지원합니다.
* indeterminate prop을 통해 부분 선택 상태를 표시할 수 있습니다.
*/
export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
({ label, className = '', indeterminate = false, ...props }, ref) => {
const internalRef = useRef<HTMLInputElement>(null);
// 외부 ref와 내부 ref를 병합
const combinedRef = (node: HTMLInputElement | null) => {
internalRef.current = node;
if (typeof ref === 'function') {
ref(node);
} else if (ref) {
ref.current = node;
}
};
// indeterminate 상태 설정 (DOM 속성이므로 JavaScript로 설정해야 함)
useEffect(() => {
if (internalRef.current) {
internalRef.current.indeterminate = indeterminate;
}
}, [indeterminate]);
return (
<input
ref={combinedRef}
type="checkbox"
className={className}
{...props}
/>
);
}
);
Checkbox.displayName = 'Checkbox';
@@ -0,0 +1,24 @@
import React from 'react';
export interface CodeProps extends React.HTMLAttributes<HTMLElement> {}
/**
* 기본 code 컴포넌트
*
* 인라인 코드 또는 코드 스니펫을 표시하기 위한 기본 컴포넌트입니다.
* HTML <code> 태그를 래핑합니다.
*/
export const Code: React.FC<CodeProps> = ({
children,
className = '',
...props
}) => {
return (
<code
className={className}
{...props}
>
{children}
</code>
);
};
@@ -0,0 +1,24 @@
import React from 'react';
export interface DivProps extends React.HTMLAttributes<HTMLDivElement> {
ref?: React.Ref<HTMLDivElement>;
}
/**
* 기본 div 컴포넌트
*/
export const Div = React.forwardRef<HTMLDivElement, DivProps>(({
children,
className = '',
...props
}, ref) => {
return (
<div
ref={ref}
className={className}
{...props}
>
{children}
</div>
);
});
@@ -0,0 +1,116 @@
import React, { forwardRef, useRef, useCallback, useState } from 'react';
export interface FileInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type' | 'onChange' | 'onError'> {
/** 허용되는 파일 확장자 (예: ".zip,.pdf") */
accept?: string;
/** 최대 파일 크기 (MB) */
maxSize?: number;
/** 파일 선택 시 콜백 */
onChange?: (file: File | null) => void;
/** 에러 발생 시 콜백 */
onError?: (error: string) => void;
/** 버튼 텍스트 */
buttonText?: string;
/** 빈 상태 텍스트 */
placeholder?: string;
}
/**
* 파일 업로드 입력 컴포넌트
*
* ZIP 파일 등의 파일 업로드를 처리하며, 파일 크기 검증을 지원합니다.
*/
export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
accept,
maxSize,
onChange,
onError,
buttonText = 'Browse',
placeholder = 'No file selected',
className = '',
disabled,
...props
}, ref) => {
const internalRef = useRef<HTMLInputElement>(null);
const inputRef = (ref as React.RefObject<HTMLInputElement>) || internalRef;
const [fileName, setFileName] = useState<string>('');
const handleClick = useCallback(() => {
if (!disabled && inputRef.current) {
inputRef.current.click();
}
}, [disabled, inputRef]);
const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0] || null;
if (!file) {
setFileName('');
onChange?.(null);
return;
}
// 파일 크기 검증 (MB 단위)
if (maxSize && file.size > maxSize * 1024 * 1024) {
const errorMsg = `File size exceeds ${maxSize}MB limit`;
onError?.(errorMsg);
// 입력 초기화
if (inputRef.current) {
inputRef.current.value = '';
}
setFileName('');
return;
}
setFileName(file.name);
onChange?.(file);
}, [maxSize, onChange, onError, inputRef]);
const handleClear = useCallback((e: React.MouseEvent) => {
e.stopPropagation();
if (inputRef.current) {
inputRef.current.value = '';
}
setFileName('');
onChange?.(null);
}, [onChange, inputRef]);
return (
<div className={`flex items-center gap-2 ${className}`}>
<input
ref={inputRef}
type="file"
accept={accept}
onChange={handleChange}
disabled={disabled}
className="hidden"
{...props}
/>
<button
type="button"
onClick={handleClick}
disabled={disabled}
className="px-4 py-2 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
>
{buttonText}
</button>
<span className="flex-1 text-sm text-gray-600 dark:text-gray-400 truncate">
{fileName || placeholder}
</span>
{fileName && !disabled && (
<button
type="button"
onClick={handleClear}
className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
aria-label="Clear file"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
);
});
FileInput.displayName = 'FileInput';
@@ -0,0 +1,21 @@
import React from 'react';
export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> {}
/**
* 기본 form 컴포넌트
*/
export const Form: React.FC<FormProps> = ({
children,
className = '',
...props
}) => {
return (
<form
className={className}
{...props}
>
{children}
</form>
);
};
@@ -0,0 +1,35 @@
import React from 'react';
export interface FragmentProps {
children?: React.ReactNode;
className?: string;
style?: React.CSSProperties;
}
/**
* Fragment 기본 컴포넌트
*
* React.Fragment와 유사하게 DOM 요소를 추가하지 않고 children만 렌더링합니다.
* iterator와 함께 사용하여 불필요한 wrapper div 없이 반복 렌더링할 때 유용합니다.
*
* @example
* // 레이아웃 JSON 사용 예시
* {
* "type": "basic",
* "name": "Fragment",
* "iterator": {
* "source": "{{items}}",
* "item": "item"
* },
* "children": [
* {
* "type": "basic",
* "name": "Button",
* "text": "{{item.label}}"
* }
* ]
* }
*/
export const Fragment: React.FC<FragmentProps> = ({ children }) => {
return <>{children}</>;
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface H1Props extends React.HTMLAttributes<HTMLHeadingElement> {}
/**
* 기본 h1 제목 컴포넌트
*/
export const H1: React.FC<H1Props> = ({
children,
className = '',
...props
}) => {
return (
<h1
className={className}
{...props}
>
{children}
</h1>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface H2Props extends React.HTMLAttributes<HTMLHeadingElement> {}
/**
* 기본 h2 제목 컴포넌트
*/
export const H2: React.FC<H2Props> = ({
children,
className = '',
...props
}) => {
return (
<h2
className={className}
{...props}
>
{children}
</h2>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface H3Props extends React.HTMLAttributes<HTMLHeadingElement> {}
/**
* 기본 h3 제목 컴포넌트
*/
export const H3: React.FC<H3Props> = ({
children,
className = '',
...props
}) => {
return (
<h3
className={className}
{...props}
>
{children}
</h3>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface H4Props extends React.HTMLAttributes<HTMLHeadingElement> {}
/**
* 기본 h4 제목 컴포넌트
*/
export const H4: React.FC<H4Props> = ({
children,
className = '',
...props
}) => {
return (
<h4
className={className}
{...props}
>
{children}
</h4>
);
};
@@ -0,0 +1,18 @@
import React from 'react';
export interface HrProps extends React.HTMLAttributes<HTMLHRElement> {}
/**
* 기본 hr(수평선) 컴포넌트
*/
export const Hr: React.FC<HrProps> = ({
className = '',
...props
}) => {
return (
<hr
className={className}
{...props}
/>
);
};
@@ -0,0 +1,27 @@
import React from 'react';
export interface IProps extends React.HTMLAttributes<HTMLElement> {
className?: string;
children?: React.ReactNode;
style?: React.CSSProperties;
}
/**
* I 기본 컴포넌트
*
* HTML <i> 태그를 래핑한 기본 컴포넌트입니다.
* 주로 아이콘 폰트 (FontAwesome 등)와 함께 사용됩니다.
*
* @example
* ```tsx
* <I className="fas fa-user" />
* <I className="fas fa-home" />
* ```
*/
export const I: React.FC<IProps> = ({ className = '', children, style, ...props }) => {
return (
<i className={className} style={style} {...props}>
{children}
</i>
);
};
@@ -0,0 +1,166 @@
import React from 'react';
import { IconName, IconStyle, IconSize } from './IconTypes';
export interface IconProps extends Omit<React.HTMLAttributes<HTMLElement>, 'style'> {
/**
* 아이콘 이름 (Font Awesome 클래스명 또는 IconName enum)
*
* @example
* // 문자열로 직접 지정
* <Icon name="fa-user" />
*
* // enum 사용 (타입 안전)
* <Icon name={IconName.User} />
*/
name: string | IconName;
/**
* 아이콘 스타일 (Font Awesome 5/6)
*
* - solid: fas (기본값)
* - regular: far
* - light: fal
* - duotone: fad
* - brands: fab
*/
iconStyle?: IconStyle;
/**
* CSS 스타일 객체 (HTML style 속성)
*/
style?: React.CSSProperties;
/**
* 아이콘 크기
*
* @default 'md'
*/
size?: IconSize;
/**
* 색상 (Tailwind 클래스 또는 CSS 색상)
*/
color?: string;
/**
* 회전 애니메이션 활성화
*/
spin?: boolean;
/**
* 펄스 애니메이션 활성화 (8단계 회전)
*/
pulse?: boolean;
/**
* 고정 너비 (아이콘 정렬 시 유용)
*/
fixedWidth?: boolean;
/**
* 접근성 레이블 (자동 생성 가능)
*/
ariaLabel?: string;
}
/**
* Font Awesome 아이콘 컴포넌트
*
* Font Awesome 5/6 버전과 호환되며 다양한 props를 지원합니다.
*
* @example
* // 기본 사용
* <Icon name="fa-user" />
*
* // enum 사용 (타입 안전)
* <Icon name={IconName.Search} />
*
* // 스타일 및 크기 지정
* <Icon name={IconName.Heart} style="regular" size="2x" />
*
* // 애니메이션
* <Icon name={IconName.Spinner} spin />
* <Icon name={IconName.CircleNotch} pulse />
*
* // 색상 지정
* <Icon name={IconName.Star} color="text-yellow-500" />
*
* // 접근성
* <Icon name={IconName.User} ariaLabel="사용자 프로필" />
*/
export const Icon: React.FC<IconProps> = ({
name,
iconStyle = 'solid',
size,
color,
spin = false,
pulse = false,
fixedWidth = false,
ariaLabel,
className = '',
style,
...props
}) => {
// Font Awesome 스타일 클래스 매핑
const styleClassMap: Record<IconStyle, string> = {
solid: 'fas',
regular: 'far',
light: 'fal',
duotone: 'fad',
brands: 'fab',
};
// 스타일 접두사를 IconStyle로 변환하는 매핑
const stylePrefixMap: Record<string, IconStyle> = {
'fa-solid': 'solid',
'fa-regular': 'regular',
'fa-light': 'light',
'fa-duotone': 'duotone',
'fa-brands': 'brands',
};
const nameStr = typeof name === 'string' ? name : String(name);
// "fa-regular fa-pen-to-square" 형식 파싱
let resolvedStyle = iconStyle;
let iconName = nameStr;
// 스타일 접두사가 포함된 경우 파싱 (예: "fa-regular fa-pen-to-square")
for (const [prefix, styleValue] of Object.entries(stylePrefixMap)) {
if (nameStr.startsWith(prefix + ' ')) {
resolvedStyle = styleValue;
iconName = nameStr.substring(prefix.length + 1); // 스타일 접두사와 공백 제거
break;
}
}
// 아이콘 이름에서 'fa-' 접두사 제거 (이미 있으면)
iconName = iconName.replace(/^fa-/, '');
// 클래스 조합
const classes = [
styleClassMap[resolvedStyle],
`fa-${iconName}`,
size && `fa-${size}`,
spin && 'fa-spin',
pulse && 'fa-pulse',
fixedWidth && 'fa-fw',
color,
className,
]
.filter(Boolean)
.join(' ');
// 접근성: ariaLabel이 없으면 name에서 생성
const accessibilityLabel = ariaLabel || iconName.replace(/-/g, ' ');
return (
<i
className={classes}
style={style}
aria-label={accessibilityLabel}
role="img"
{...props}
/>
);
};
@@ -0,0 +1,291 @@
/**
* Font Awesome 아이콘 스타일
*/
export type IconStyle = 'solid' | 'regular' | 'light' | 'duotone' | 'brands';
/**
* Font Awesome 아이콘 크기
*/
export type IconSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2x' | '3x' | '4x' | '5x';
/**
* 자주 사용되는 Font Awesome 아이콘 이름
*
* @example
* // 사용 예시
* <Icon name="user" />
* <Icon name="search" />
* <Icon name="shopping-cart" />
*/
export enum IconName {
// 사용자 및 계정
User = 'fa-user',
Users = 'fa-users',
UserCircle = 'fa-user-circle',
UserPlus = 'fa-user-plus',
UserMinus = 'fa-user-minus',
UserShield = 'fa-user-shield',
// 액션 아이콘
Search = 'fa-search',
Edit = 'fa-edit',
Pencil = 'fa-pencil-alt',
Trash = 'fa-trash',
Save = 'fa-save',
Plus = 'fa-plus',
Minus = 'fa-minus',
Check = 'fa-check',
Times = 'fa-times',
Download = 'fa-download',
Upload = 'fa-upload',
Copy = 'fa-copy',
ExternalLink = 'fa-external-link-alt',
// 네비게이션
Home = 'fa-home',
CaretRight = 'fa-caret-right',
CaretDown = 'fa-caret-down',
ChevronLeft = 'fa-chevron-left',
ChevronRight = 'fa-chevron-right',
ChevronUp = 'fa-chevron-up',
ChevronDown = 'fa-chevron-down',
AngleLeft = 'fa-angle-left',
AngleRight = 'fa-angle-right',
AngleUp = 'fa-angle-up',
AngleDown = 'fa-angle-down',
ArrowUp = 'fa-arrow-up',
ArrowDown = 'fa-arrow-down',
ArrowLeft = 'fa-arrow-left',
ArrowRight = 'fa-arrow-right',
Bars = 'fa-bars',
EllipsisVertical = 'fa-ellipsis-v',
EllipsisHorizontal = 'fa-ellipsis-h',
// 상태 아이콘
CheckCircle = 'fa-check-circle',
TimesCircle = 'fa-times-circle',
ExclamationCircle = 'fa-exclamation-circle',
ExclamationTriangle = 'fa-exclamation-triangle',
InfoCircle = 'fa-info-circle',
QuestionCircle = 'fa-question-circle',
XCircle = 'fa-times-circle',
// 이커머스
ShoppingCart = 'fa-shopping-cart',
ShoppingBag = 'fa-shopping-bag',
CreditCard = 'fa-credit-card',
Tag = 'fa-tag',
Tags = 'fa-tags',
// 파일 및 문서
File = 'fa-file',
FileAlt = 'fa-file-alt',
Folder = 'fa-folder',
FolderOpen = 'fa-folder-open',
// 통신
Envelope = 'fa-envelope',
Phone = 'fa-phone',
Comment = 'fa-comment',
Comments = 'fa-comments',
// 설정
Cog = 'fa-cog',
Cogs = 'fa-cogs',
Settings = 'fa-cog',
Wrench = 'fa-wrench',
Sliders = 'fa-sliders-h',
// 미디어
Image = 'fa-image',
Images = 'fa-images',
Video = 'fa-video',
Camera = 'fa-camera',
// 소셜
Heart = 'fa-heart',
Star = 'fa-star',
ThumbsUp = 'fa-thumbs-up',
ThumbsDown = 'fa-thumbs-down',
Share = 'fa-share',
// 시간
Clock = 'fa-clock',
Calendar = 'fa-calendar',
CalendarAlt = 'fa-calendar-alt',
// 기타
Lock = 'fa-lock',
Unlock = 'fa-unlock',
Eye = 'fa-eye',
EyeSlash = 'fa-eye-slash',
Bell = 'fa-bell',
Flag = 'fa-flag',
Map = 'fa-map',
MapMarker = 'fa-map-marker-alt',
Globe = 'fa-globe',
Link = 'fa-link',
Unlink = 'fa-unlink',
Sun = 'fa-sun',
Moon = 'fa-moon',
// 차트 및 통계
ChartBar = 'fa-chart-bar',
ChartLine = 'fa-chart-line',
ChartPie = 'fa-chart-pie',
ChartArea = 'fa-chart-area',
// 스피너 (로딩)
Spinner = 'fa-spinner',
CircleNotch = 'fa-circle-notch',
// 배지 아이콘
CheckBadge = 'fa-badge-check',
// 확장 시스템 (모듈/플러그인/템플릿)
Cube = 'fa-cube',
Cubes = 'fa-cubes',
Plug = 'fa-plug',
PuzzlePiece = 'fa-puzzle-piece',
Palette = 'fa-palette',
}
/**
* 문자열 아이콘 이름을 IconName enum으로 매핑합니다.
* JSON 레이아웃에서 문자열로 아이콘 이름을 지정할 때 사용합니다.
*/
export const iconNameMap: Record<string, IconName> = {
// 사용자 및 계정
'user': IconName.User,
'users': IconName.Users,
'user-circle': IconName.UserCircle,
'user-plus': IconName.UserPlus,
'user-minus': IconName.UserMinus,
'user-shield': IconName.UserShield,
// 액션 아이콘
'search': IconName.Search,
'edit': IconName.Edit,
'pencil': IconName.Pencil,
'trash': IconName.Trash,
'save': IconName.Save,
'plus': IconName.Plus,
'minus': IconName.Minus,
'check': IconName.Check,
'times': IconName.Times,
'download': IconName.Download,
'upload': IconName.Upload,
'copy': IconName.Copy,
'external-link': IconName.ExternalLink,
// 네비게이션
'home': IconName.Home,
'caret-right': IconName.CaretRight,
'caret-down': IconName.CaretDown,
'chevron-left': IconName.ChevronLeft,
'chevron-right': IconName.ChevronRight,
'chevron-up': IconName.ChevronUp,
'chevron-down': IconName.ChevronDown,
'angle-left': IconName.AngleLeft,
'angle-right': IconName.AngleRight,
'angle-up': IconName.AngleUp,
'angle-down': IconName.AngleDown,
'arrow-up': IconName.ArrowUp,
'arrow-down': IconName.ArrowDown,
'arrow-left': IconName.ArrowLeft,
'arrow-right': IconName.ArrowRight,
'bars': IconName.Bars,
'ellipsis-vertical': IconName.EllipsisVertical,
'ellipsis-v': IconName.EllipsisVertical,
'ellipsis-horizontal': IconName.EllipsisHorizontal,
'ellipsis-h': IconName.EllipsisHorizontal,
// 상태 아이콘
'check-circle': IconName.CheckCircle,
'times-circle': IconName.TimesCircle,
'x-circle': IconName.XCircle,
'exclamation-circle': IconName.ExclamationCircle,
'exclamation-triangle': IconName.ExclamationTriangle,
'info-circle': IconName.InfoCircle,
'question-circle': IconName.QuestionCircle,
// 이커머스
'shopping-cart': IconName.ShoppingCart,
'shopping-bag': IconName.ShoppingBag,
'credit-card': IconName.CreditCard,
'tag': IconName.Tag,
'tags': IconName.Tags,
// 파일 및 문서
'file': IconName.File,
'file-alt': IconName.FileAlt,
'folder': IconName.Folder,
'folder-open': IconName.FolderOpen,
// 통신
'envelope': IconName.Envelope,
'phone': IconName.Phone,
'comment': IconName.Comment,
'comments': IconName.Comments,
// 설정
'cog': IconName.Cog,
'cogs': IconName.Cogs,
'settings': IconName.Settings,
'wrench': IconName.Wrench,
'sliders': IconName.Sliders,
// 미디어
'image': IconName.Image,
'images': IconName.Images,
'video': IconName.Video,
'camera': IconName.Camera,
// 소셜
'heart': IconName.Heart,
'star': IconName.Star,
'thumbs-up': IconName.ThumbsUp,
'thumbs-down': IconName.ThumbsDown,
'share': IconName.Share,
// 시간
'clock': IconName.Clock,
'calendar': IconName.Calendar,
'calendar-alt': IconName.CalendarAlt,
// 기타
'lock': IconName.Lock,
'unlock': IconName.Unlock,
'eye': IconName.Eye,
'eye-slash': IconName.EyeSlash,
'bell': IconName.Bell,
'flag': IconName.Flag,
'map': IconName.Map,
'map-marker': IconName.MapMarker,
'globe': IconName.Globe,
'link': IconName.Link,
'unlink': IconName.Unlink,
'sun': IconName.Sun,
'moon': IconName.Moon,
// 차트 및 통계
'chart-bar': IconName.ChartBar,
'chart-line': IconName.ChartLine,
'chart-pie': IconName.ChartPie,
'chart-area': IconName.ChartArea,
// 스피너 (로딩)
'spinner': IconName.Spinner,
'circle-notch': IconName.CircleNotch,
// 배지 아이콘
'check-badge': IconName.CheckBadge,
'badge-check': IconName.CheckBadge,
// 확장 시스템 (모듈/플러그인/템플릿)
'cube': IconName.Cube,
'cubes': IconName.Cubes,
'plug': IconName.Plug,
'puzzle-piece': IconName.PuzzlePiece,
'palette': IconName.Palette,
};
@@ -0,0 +1,20 @@
import React from 'react';
export interface ImgProps extends React.ImgHTMLAttributes<HTMLImageElement> {}
/**
* 기본 이미지 컴포넌트
*/
export const Img: React.FC<ImgProps> = ({
className = '',
alt = '',
...props
}) => {
return (
<img
className={className}
alt={alt}
{...props}
/>
);
};
@@ -0,0 +1,159 @@
import React, { useRef, useCallback, useState, useEffect, forwardRef, useImperativeHandle } from 'react';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
label?: string;
error?: string;
}
/**
* 기본 입력 필드 컴포넌트
*
* IME(한글 등) 조합 중에는 외부 onChange 이벤트를 발생시키지 않습니다.
* 내부 로컬 상태를 사용하여 입력을 처리하고, 조합이 완료되면 외부에 알립니다.
*
* forwardRef를 사용하여 외부에서 ref로 input 요소에 접근할 수 있습니다.
* 예: indeterminate 상태 설정 시 ref.current.indeterminate = true
*/
export const Input = forwardRef<HTMLInputElement, InputProps>(({
label,
error,
className = '',
onChange,
onKeyPress,
value,
defaultValue,
type = 'text',
checked,
defaultChecked,
...props
}, ref) => {
// radio/checkbox 타입인지 확인
const isCheckableType = type === 'radio' || type === 'checkbox';
// IME 조합 중인지 추적 (text input에만 필요)
const isComposingRef = useRef(false);
// input 요소 참조
const internalRef = useRef<HTMLInputElement>(null);
// 외부 ref와 내부 ref를 연결
useImperativeHandle(ref, () => internalRef.current as HTMLInputElement);
// 내부 로컬 값 (IME 조합 중에도 화면에 표시됨) - text input에만 사용
const [localValue, setLocalValue] = useState<string>(
(value as string) ?? (defaultValue as string) ?? ''
);
// 외부 value prop이 변경되면 로컬 값도 동기화 (text input에만 적용)
// 단, 사용자가 입력 중(포커스 상태)이면 동기화 건너뜀 (debounce 대기 중 stale value 플리커 방지)
useEffect(() => {
if (!isCheckableType && !isComposingRef.current && value !== undefined) {
const isFocused = internalRef.current && document.activeElement === internalRef.current;
if (isFocused) {
return;
}
setLocalValue(value as string);
}
}, [value, isCheckableType]);
const handleCompositionStart = useCallback(() => {
isComposingRef.current = true;
}, []);
const handleCompositionEnd = useCallback(
(e: React.CompositionEvent<HTMLInputElement>) => {
isComposingRef.current = false;
// 조합 완료 후 onChange 이벤트 발생
if (onChange) {
// 현재 input의 실제 값을 사용
const currentValue = (e.target as HTMLInputElement).value;
setLocalValue(currentValue);
// 새로운 ChangeEvent 생성
const changeEvent = new Event('change', { bubbles: true }) as unknown as React.ChangeEvent<HTMLInputElement>;
Object.defineProperty(changeEvent, 'target', {
writable: false,
value: { value: currentValue },
});
Object.defineProperty(changeEvent, 'currentTarget', {
writable: false,
value: { value: currentValue },
});
onChange(changeEvent);
}
},
[onChange]
);
const handleChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
// 항상 로컬 값은 업데이트 (화면에 입력이 보이도록)
setLocalValue(newValue);
// IME 조합 중이면 외부 onChange를 호출하지 않음
if (isComposingRef.current) {
return;
}
if (onChange) {
onChange(e);
}
},
[onChange]
);
const handleKeyPress = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
// IME 조합 중이면 keypress 무시 (Enter 등)
if (isComposingRef.current) {
return;
}
if (onKeyPress) {
onKeyPress(e);
}
},
[onKeyPress]
);
// HTML 표준 속성이 아닌 것들을 필터링 (템플릿 엔진 내부 속성)
const { loadingactions, formdata, ...validProps } = props as any;
// radio/checkbox: checked 속성 사용
// text input: value 속성 사용 (IME 처리 포함)
if (isCheckableType) {
return (
<input
ref={internalRef}
type={type}
className={className}
onChange={onChange}
checked={checked}
defaultChecked={defaultChecked}
value={value}
{...validProps}
/>
);
}
// text input: controlled/uncontrolled 구분
const inputProps = value !== undefined
? { value: localValue }
: { defaultValue };
return (
<input
ref={internalRef}
type={type}
className={className}
onChange={handleChange}
onKeyPress={handleKeyPress}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
{...inputProps}
{...validProps}
/>
);
});
// displayName 설정 (React DevTools에서 컴포넌트 이름 표시)
Input.displayName = 'Input';
@@ -0,0 +1,21 @@
import React from 'react';
export interface LabelProps extends React.LabelHTMLAttributes<HTMLLabelElement> {}
/**
* 기본 레이블 컴포넌트
*/
export const Label: React.FC<LabelProps> = ({
children,
className = '',
...props
}) => {
return (
<label
className={className}
{...props}
>
{children}
</label>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface LiProps extends React.LiHTMLAttributes<HTMLLIElement> {}
/**
* 기본 li(목록 항목) 컴포넌트
*/
export const Li: React.FC<LiProps> = ({
children,
className = '',
...props
}) => {
return (
<li
className={className}
{...props}
>
{children}
</li>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface NavProps extends React.HTMLAttributes<HTMLElement> {}
/**
* 기본 nav 컴포넌트
*/
export const Nav: React.FC<NavProps> = ({
children,
className = '',
...props
}) => {
return (
<nav
className={className}
{...props}
>
{children}
</nav>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface OlProps extends React.HTMLAttributes<HTMLOListElement> {}
/**
* 기본 ol(순서있는 목록) 컴포넌트
*/
export const Ol: React.FC<OlProps> = ({
children,
className = '',
...props
}) => {
return (
<ol
className={className}
{...props}
>
{children}
</ol>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface OptgroupProps extends React.OptgroupHTMLAttributes<HTMLOptGroupElement> {}
/**
* 기본 optgroup 컴포넌트 (Select 내부에서 옵션 그룹화)
*/
export const Optgroup: React.FC<OptgroupProps> = ({
children,
className = '',
...props
}) => {
return (
<optgroup
className={className}
{...props}
>
{children}
</optgroup>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface OptionProps extends React.OptionHTMLAttributes<HTMLOptionElement> {}
/**
* 기본 option 컴포넌트 (Select 내부에서 사용)
*/
export const Option: React.FC<OptionProps> = ({
children,
className = '',
...props
}) => {
return (
<option
className={className}
{...props}
>
{children}
</option>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface PProps extends React.HTMLAttributes<HTMLParagraphElement> {}
/**
* 기본 p(단락) 컴포넌트
*/
export const P: React.FC<PProps> = ({
children,
className = '',
...props
}) => {
return (
<p
className={className}
{...props}
>
{children}
</p>
);
};
@@ -0,0 +1,24 @@
import React from 'react';
export interface PreProps extends React.HTMLAttributes<HTMLPreElement> {}
/**
* 기본 pre 컴포넌트
*
* 서식이 지정된 텍스트를 표시하기 위한 기본 컴포넌트입니다.
* HTML <pre> 태그를 래핑합니다.
*/
export const Pre: React.FC<PreProps> = ({
children,
className = '',
...props
}) => {
return (
<pre
className={className}
{...props}
>
{children}
</pre>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface SectionProps extends React.HTMLAttributes<HTMLElement> {}
/**
* 기본 section 컴포넌트
*/
export const Section: React.FC<SectionProps> = ({
children,
className = '',
...props
}) => {
return (
<section
className={className}
{...props}
>
{children}
</section>
);
};
@@ -0,0 +1,232 @@
import React, { useMemo, useState, useRef, useEffect } from 'react';
import { Div } from './Div';
import { Button } from './Button';
import { Span } from './Span';
import { Svg } from './Svg';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Comp:Select')) ?? {
log: (...args: unknown[]) => console.log('[Comp:Select]', ...args),
warn: (...args: unknown[]) => console.warn('[Comp:Select]', ...args),
error: (...args: unknown[]) => console.error('[Comp:Select]', ...args),
};
export interface SelectOption {
value: string | number;
label: string;
disabled?: boolean;
}
export interface SelectProps extends Omit<React.SelectHTMLAttributes<HTMLSelectElement>, 'onChange'> {
label?: string;
error?: string;
options?: SelectOption[] | string[];
onChange?: (e: React.ChangeEvent<HTMLSelectElement> | { target: { value: string | number } }) => void;
}
/**
* 로케일 코드를 사람이 읽을 수 있는 이름으로 변환
*/
function getLocaleName(locale: string): string {
const localeNames: Record<string, string> = {
ko: '한국어',
en: 'English',
ja: '日本語',
zh: '中文',
es: 'Español',
fr: 'Français',
de: 'Deutsch',
};
return localeNames[locale] || locale;
}
/**
* 커스텀 Select 컴포넌트
*
* options prop을 사용하여 드롭다운 메뉴를 생성합니다.
* 둥근 모서리, 그림자, 체크마크가 있는 커스텀 스타일을 지원합니다.
*/
export const Select: React.FC<SelectProps> = ({
children,
label,
error,
options,
className = '',
value,
onChange,
disabled,
...props
}) => {
const [isOpen, setIsOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
// options를 SelectOption[] 형식으로 정규화
const normalizedOptions = useMemo((): SelectOption[] | null => {
if (!options) return null;
// 배열이 아닌 경우 (바인딩 에러 또는 잘못된 prop)
if (!Array.isArray(options)) {
logger.warn('options prop is not an array:', options);
return null;
}
// 빈 배열인 경우
if (options.length === 0) return [];
// string[] 배열인 경우
if (typeof options[0] === 'string') {
return (options as string[]).map((locale): SelectOption => ({
value: locale,
label: getLocaleName(locale),
}));
}
// SelectOption[] 배열인 경우 (기존 동작)
return options as SelectOption[];
}, [options]);
// 현재 선택된 옵션의 라벨 가져오기
const selectedLabel = useMemo(() => {
if (!normalizedOptions) return '';
const selected = normalizedOptions.find(opt => String(opt.value) === String(value));
return selected?.label || '';
}, [normalizedOptions, value]);
// 외부 클릭 시 드롭다운 닫기
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
};
if (isOpen) {
document.addEventListener('mousedown', handleClickOutside);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [isOpen]);
// ESC 키로 드롭다운 닫기
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape' && isOpen) {
setIsOpen(false);
buttonRef.current?.focus();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [isOpen]);
const handleToggle = () => {
if (!disabled) {
setIsOpen(!isOpen);
}
};
const handleSelect = (optionValue: string | number) => {
if (onChange) {
// ActionDispatcher가 이벤트를 인식할 수 있도록 preventDefault 메서드 포함
const syntheticEvent = {
target: { value: optionValue },
preventDefault: () => {},
stopPropagation: () => {},
type: 'change',
};
onChange(syntheticEvent as any);
}
setIsOpen(false);
buttonRef.current?.focus();
};
// options가 없으면 기본 select 사용 (children 지원)
if (!normalizedOptions) {
return (
<select
className={className}
value={value}
onChange={onChange as React.ChangeEventHandler<HTMLSelectElement>}
disabled={disabled}
{...props}
>
{children}
</select>
);
}
// 기본 스타일 (className이 없을 때 적용)
const hasCustomStyle = className && className.includes('bg-');
// 커스텀 스타일에 텍스트 색상이 없으면 기본 텍스트 색상 보충
const hasTextColor = className && /text-(gray|red|blue|green|yellow|white|black|indigo|purple|pink|orange|amber|emerald|teal|cyan|slate)-\d+|text-white|text-black/.test(className);
const baseButtonClass = hasCustomStyle
? `${className}${hasTextColor ? '' : ' text-gray-700 dark:text-gray-200'}`
: `w-full px-4 py-2.5 bg-gray-100 dark:bg-gray-700 border-0 rounded-xl text-gray-700 dark:text-gray-200 font-medium focus:ring-2 focus:ring-blue-500 focus:outline-none ${className}`;
return (
<Div ref={containerRef} className="relative">
<Button
ref={buttonRef}
type="button"
onClick={handleToggle}
disabled={disabled}
className={`${baseButtonClass} flex items-center justify-between gap-2 text-left cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed`}
aria-haspopup="listbox"
aria-expanded={isOpen}
>
<Span className="truncate">{selectedLabel || '\u00A0'}</Span>
<Svg
className={`w-4 h-4 flex-shrink-0 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</Svg>
</Button>
{isOpen && (
<Div
className="absolute z-50 w-full mt-2 bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-600 overflow-hidden"
role="listbox"
>
<Div className="py-2 max-h-60 overflow-auto">
{normalizedOptions.map((option) => {
const isSelected = String(option.value) === String(value);
return (
<Button
key={option.value}
type="button"
onClick={() => !option.disabled && handleSelect(option.value)}
disabled={option.disabled}
className={`w-full px-4 py-3 text-left flex items-center justify-between hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${
isSelected ? 'text-blue-600 dark:text-blue-400 font-medium' : 'text-gray-700 dark:text-gray-200'
} ${option.disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
role="option"
aria-selected={isSelected}
>
<Span>{option.label}</Span>
{isSelected && (
<Svg
className="w-5 h-5 text-blue-600 dark:text-blue-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</Svg>
)}
</Button>
);
})}
</Div>
</Div>
)}
</Div>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface SpanProps extends React.HTMLAttributes<HTMLSpanElement> {}
/**
* 기본 span 컴포넌트
*/
export const Span: React.FC<SpanProps> = ({
children,
className = '',
...props
}) => {
return (
<span
className={className}
{...props}
>
{children}
</span>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface SvgProps extends React.SVGAttributes<SVGSVGElement> {}
/**
* 기본 svg 컴포넌트
*/
export const Svg: React.FC<SvgProps> = ({
children,
className = '',
...props
}) => {
return (
<svg
className={className}
{...props}
>
{children}
</svg>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TableProps extends React.TableHTMLAttributes<HTMLTableElement> {}
/**
* 기본 table 컴포넌트
*/
export const Table: React.FC<TableProps> = ({
children,
className = '',
...props
}) => {
return (
<table
className={className}
{...props}
>
{children}
</table>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TbodyProps extends React.HTMLAttributes<HTMLTableSectionElement> {}
/**
* 기본 tbody 컴포넌트
*/
export const Tbody: React.FC<TbodyProps> = ({
children,
className = '',
...props
}) => {
return (
<tbody
className={className}
{...props}
>
{children}
</tbody>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TdProps extends React.TdHTMLAttributes<HTMLTableCellElement> {}
/**
* 기본 td(테이블 데이터 셀) 컴포넌트
*/
export const Td: React.FC<TdProps> = ({
children,
className = '',
...props
}) => {
return (
<td
className={className}
{...props}
>
{children}
</td>
);
};
@@ -0,0 +1,106 @@
import React, { useRef, useCallback, useState, useEffect } from 'react';
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
label?: string;
error?: string;
}
/**
* 기본 텍스트 영역 컴포넌트
*
* IME(한글 등) 조합 중에는 외부 onChange 이벤트를 발생시키지 않습니다.
* 내부 로컬 상태를 사용하여 입력을 처리하고, 조합이 완료되면 외부에 알립니다.
*/
export const Textarea: React.FC<TextareaProps> = ({
label,
error,
className = '',
onChange,
value,
defaultValue,
...props
}) => {
// IME 조합 중인지 추적
const isComposingRef = useRef(false);
// textarea 요소 참조
const textareaRef = useRef<HTMLTextAreaElement>(null);
// 내부 로컬 값 (IME 조합 중에도 화면에 표시됨)
const [localValue, setLocalValue] = useState<string>(
(value as string) ?? (defaultValue as string) ?? ''
);
// 외부 value prop이 변경되면 로컬 값도 동기화
useEffect(() => {
if (!isComposingRef.current && value !== undefined) {
setLocalValue(value as string);
}
}, [value]);
const handleCompositionStart = useCallback(() => {
isComposingRef.current = true;
}, []);
const handleCompositionEnd = useCallback(
(e: React.CompositionEvent<HTMLTextAreaElement>) => {
isComposingRef.current = false;
// 조합 완료 후 onChange 이벤트 발생
if (onChange) {
// 현재 textarea의 실제 값을 사용
const currentValue = (e.target as HTMLTextAreaElement).value;
setLocalValue(currentValue);
// 새로운 ChangeEvent 생성
const changeEvent = new Event('change', { bubbles: true }) as unknown as React.ChangeEvent<HTMLTextAreaElement>;
Object.defineProperty(changeEvent, 'target', {
writable: false,
value: { value: currentValue },
});
Object.defineProperty(changeEvent, 'currentTarget', {
writable: false,
value: { value: currentValue },
});
onChange(changeEvent);
}
},
[onChange]
);
const handleChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
const newValue = e.target.value;
// 항상 로컬 값은 업데이트 (화면에 입력이 보이도록)
setLocalValue(newValue);
// IME 조합 중이면 외부 onChange를 호출하지 않음
if (isComposingRef.current) {
return;
}
if (onChange) {
onChange(e);
}
},
[onChange]
);
// HTML 표준 속성이 아닌 것들을 필터링 (템플릿 엔진 내부 속성)
const { loadingactions, formdata, ...validProps } = props as any;
// controlled/uncontrolled 구분
const textareaValueProps = value !== undefined
? { value: localValue }
: { defaultValue };
return (
<textarea
ref={textareaRef}
className={className}
onChange={handleChange}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
{...textareaValueProps}
{...validProps}
/>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TfootProps extends React.HTMLAttributes<HTMLTableSectionElement> {}
/**
* 기본 tfoot 컴포넌트
*/
export const Tfoot: React.FC<TfootProps> = ({
children,
className = '',
...props
}) => {
return (
<tfoot
className={className}
{...props}
>
{children}
</tfoot>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface ThProps extends React.ThHTMLAttributes<HTMLTableCellElement> {}
/**
* 기본 th(테이블 헤더 셀) 컴포넌트
*/
export const Th: React.FC<ThProps> = ({
children,
className = '',
...props
}) => {
return (
<th
className={className}
{...props}
>
{children}
</th>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TheadProps extends React.HTMLAttributes<HTMLTableSectionElement> {}
/**
* 기본 thead 컴포넌트
*/
export const Thead: React.FC<TheadProps> = ({
children,
className = '',
...props
}) => {
return (
<thead
className={className}
{...props}
>
{children}
</thead>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface TrProps extends React.HTMLAttributes<HTMLTableRowElement> {}
/**
* 기본 tr(테이블 행) 컴포넌트
*/
export const Tr: React.FC<TrProps> = ({
children,
className = '',
...props
}) => {
return (
<tr
className={className}
{...props}
>
{children}
</tr>
);
};
@@ -0,0 +1,21 @@
import React from 'react';
export interface UlProps extends React.HTMLAttributes<HTMLUListElement> {}
/**
* 기본 ul(순서없는 목록) 컴포넌트
*/
export const Ul: React.FC<UlProps> = ({
children,
className = '',
...props
}) => {
return (
<ul
className={className}
{...props}
>
{children}
</ul>
);
};
@@ -0,0 +1,156 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Button } from '../Button';
describe('Button 컴포넌트', () => {
describe('기본 렌더링', () => {
it('자식 요소를 렌더링한다', () => {
render(<Button>클릭하기</Button>);
expect(screen.getByText('클릭하기')).toBeTruthy();
});
it('기본 variant는 primary이다', () => {
const { container } = render(<Button>버튼</Button>);
const button = container.querySelector('button');
expect(button).toBeTruthy();
});
it('기본 size는 md이다', () => {
const { container } = render(<Button>버튼</Button>);
const button = container.querySelector('button');
expect(button).toBeTruthy();
});
});
describe('Variant Props', () => {
it('primary variant가 적용된다', () => {
render(<Button variant="primary">Primary 버튼</Button>);
expect(screen.getByText('Primary 버튼')).toBeTruthy();
});
it('secondary variant가 적용된다', () => {
render(<Button variant="secondary">Secondary 버튼</Button>);
expect(screen.getByText('Secondary 버튼')).toBeTruthy();
});
it('danger variant가 적용된다', () => {
render(<Button variant="danger">Danger 버튼</Button>);
expect(screen.getByText('Danger 버튼')).toBeTruthy();
});
it('success variant가 적용된다', () => {
render(<Button variant="success">Success 버튼</Button>);
expect(screen.getByText('Success 버튼')).toBeTruthy();
});
});
describe('Size Props', () => {
it('sm size가 적용된다', () => {
render(<Button size="sm">작은 버튼</Button>);
expect(screen.getByText('작은 버튼')).toBeTruthy();
});
it('md size가 적용된다', () => {
render(<Button size="md">중간 버튼</Button>);
expect(screen.getByText('중간 버튼')).toBeTruthy();
});
it('lg size가 적용된다', () => {
render(<Button size="lg">큰 버튼</Button>);
expect(screen.getByText('큰 버튼')).toBeTruthy();
});
});
describe('이벤트 핸들링', () => {
it('onClick 핸들러가 호출된다', () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick}>클릭</Button>);
const button = screen.getByText('클릭');
fireEvent.click(button);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('disabled 상태에서는 클릭 이벤트가 발생하지 않는다', () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick} disabled>비활성 버튼</Button>);
const button = screen.getByText('비활성 버튼');
fireEvent.click(button);
expect(handleClick).not.toHaveBeenCalled();
});
});
describe('HTML 속성', () => {
it('type 속성이 적용된다', () => {
const { container } = render(<Button type="submit">제출</Button>);
const button = container.querySelector('button');
expect(button?.type).toBe('submit');
});
it('disabled 속성이 적용된다', () => {
const { container } = render(<Button disabled>비활성</Button>);
const button = container.querySelector('button');
expect(button?.disabled).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(<Button name="testButton">버튼</Button>);
const button = container.querySelector('button');
expect(button?.name).toBe('testButton');
});
it('value 속성이 적용된다', () => {
const { container } = render(<Button value="testValue">버튼</Button>);
const button = container.querySelector('button');
expect(button?.value).toBe('testValue');
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Button className="custom-button">버튼</Button>);
const button = container.querySelector('button');
expect(button?.className).toContain('custom-button');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Button aria-label="사용자 정의 레이블">버튼</Button>);
const button = container.querySelector('button');
expect(button?.getAttribute('aria-label')).toBe('사용자 정의 레이블');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Button data-testid="test-button">버튼</Button>);
const button = container.querySelector('button');
expect(button?.getAttribute('data-testid')).toBe('test-button');
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleClick = vi.fn();
const { container } = render(
<Button
variant="danger"
size="lg"
className="custom-class"
onClick={handleClick}
type="button"
>
복합 버튼
</Button>
);
const button = container.querySelector('button');
expect(button).toBeTruthy();
expect(button?.className).toContain('custom-class');
expect(button?.type).toBe('button');
fireEvent.click(button!);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
});
@@ -0,0 +1,254 @@
import { describe, it, expect, vi } from 'vitest';
import { render, fireEvent } from '@testing-library/react';
import React from 'react';
import { Checkbox } from '../Checkbox';
describe('Checkbox 컴포넌트', () => {
describe('기본 렌더링', () => {
it('checkbox 요소가 렌더링된다', () => {
const { container } = render(<Checkbox />);
const checkbox = container.querySelector('input[type="checkbox"]');
expect(checkbox).toBeTruthy();
});
it('type이 checkbox이다', () => {
const { container } = render(<Checkbox />);
const checkbox = container.querySelector('input');
expect(checkbox?.type).toBe('checkbox');
});
it('기본적으로 체크되지 않은 상태이다', () => {
const { container } = render(<Checkbox />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(false);
});
});
describe('Checked 상태', () => {
it('checked prop이 true일 때 체크된다', () => {
const { container } = render(<Checkbox checked onChange={() => {}} />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(true);
});
it('checked prop이 false일 때 체크되지 않는다', () => {
const { container } = render(<Checkbox checked={false} onChange={() => {}} />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(false);
});
it('defaultChecked prop이 적용된다', () => {
const { container } = render(<Checkbox defaultChecked />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(true);
});
});
describe('이벤트 핸들링', () => {
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Checkbox onChange={handleChange} />);
const checkbox = container.querySelector('input')!;
fireEvent.click(checkbox);
expect(handleChange).toHaveBeenCalledTimes(1);
});
it('클릭 시 체크 상태가 토글된다', () => {
const TestComponent = () => {
const [checked, setChecked] = React.useState(false);
return <Checkbox checked={checked} onChange={() => setChecked(!checked)} />;
};
const { container } = render(<TestComponent />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(false);
fireEvent.click(checkbox);
expect(checkbox.checked).toBe(true);
fireEvent.click(checkbox);
expect(checkbox.checked).toBe(false);
});
it('onFocus 핸들러가 호출된다', () => {
const handleFocus = vi.fn();
const { container } = render(<Checkbox onFocus={handleFocus} />);
const checkbox = container.querySelector('input')!;
fireEvent.focus(checkbox);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
it('onBlur 핸들러가 호출된다', () => {
const handleBlur = vi.fn();
const { container } = render(<Checkbox onBlur={handleBlur} />);
const checkbox = container.querySelector('input')!;
fireEvent.blur(checkbox);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
});
describe('HTML 속성', () => {
it('disabled 속성이 적용된다', () => {
const { container } = render(<Checkbox disabled />);
const checkbox = container.querySelector('input');
expect(checkbox?.disabled).toBe(true);
});
it('disabled 상태에서 클릭하면 상태가 변하지 않는다', () => {
const { container } = render(<Checkbox disabled />);
const checkbox = container.querySelector('input') as HTMLInputElement;
const initialChecked = checkbox.checked;
fireEvent.click(checkbox);
// disabled 상태에서도 React는 이벤트를 발생시키지만, 실제로는 변경되지 않음
expect(checkbox.disabled).toBe(true);
});
it('required 속성이 적용된다', () => {
const { container } = render(<Checkbox required />);
const checkbox = container.querySelector('input');
expect(checkbox?.required).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(<Checkbox name="terms" />);
const checkbox = container.querySelector('input');
expect(checkbox?.name).toBe('terms');
});
it('value 속성이 적용된다', () => {
const { container } = render(<Checkbox value="agree" />);
const checkbox = container.querySelector('input');
expect(checkbox?.value).toBe('agree');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Checkbox id="terms-checkbox" />);
const checkbox = container.querySelector('input');
expect(checkbox?.id).toBe('terms-checkbox');
});
it('readOnly 속성이 적용된다', () => {
const { container } = render(<Checkbox readOnly />);
const checkbox = container.querySelector('input');
expect(checkbox?.readOnly).toBe(true);
});
});
describe('Label Props', () => {
it('label prop이 존재한다', () => {
// label prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Checkbox label="약관 동의" />);
const checkbox = container.querySelector('input');
expect(checkbox).toBeTruthy();
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Checkbox className="custom-checkbox" />);
const checkbox = container.querySelector('input');
expect(checkbox?.className).toContain('custom-checkbox');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Checkbox aria-label="약관 동의" />);
const checkbox = container.querySelector('input');
expect(checkbox?.getAttribute('aria-label')).toBe('약관 동의');
});
it('checked 속성이 체크 상태를 나타낸다', () => {
const { container } = render(<Checkbox checked onChange={() => {}} />);
const checkbox = container.querySelector('input') as HTMLInputElement;
expect(checkbox.checked).toBe(true);
});
it('data 속성이 적용된다', () => {
const { container } = render(<Checkbox data-testid="test-checkbox" />);
const checkbox = container.querySelector('input');
expect(checkbox?.getAttribute('data-testid')).toBe('test-checkbox');
});
});
describe('Form 통합', () => {
it('form 제출 시 checkbox 값이 포함된다', () => {
const handleSubmit = vi.fn((e) => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
return formData.get('terms');
});
const { container } = render(
<form onSubmit={handleSubmit}>
<Checkbox name="terms" value="agree" defaultChecked />
<button type="submit">제출</button>
</form>
);
const form = container.querySelector('form')!;
fireEvent.submit(form);
expect(handleSubmit).toHaveBeenCalled();
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Checkbox
id="terms"
name="terms"
value="agree"
checked={true}
onChange={handleChange}
required
className="custom-checkbox"
aria-label="약관 동의"
/>
);
const checkbox = container.querySelector('input')!;
expect(checkbox.id).toBe('terms');
expect(checkbox.name).toBe('terms');
expect(checkbox.value).toBe('agree');
expect((checkbox as HTMLInputElement).checked).toBe(true);
expect(checkbox.required).toBe(true);
expect(checkbox.className).toContain('custom-checkbox');
expect(checkbox.getAttribute('aria-label')).toBe('약관 동의');
fireEvent.click(checkbox);
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
describe('Indeterminate 상태', () => {
it('indeterminate ref를 통해 설정할 수 있다', () => {
const TestComponent = () => {
const checkboxRef = React.useRef<HTMLInputElement>(null);
React.useEffect(() => {
if (checkboxRef.current) {
checkboxRef.current.indeterminate = true;
}
}, []);
return <Checkbox ref={checkboxRef} />;
};
const { container } = render(<TestComponent />);
const checkbox = container.querySelector('input') as HTMLInputElement;
// indeterminate는 DOM 속성이므로 직접 확인
expect(checkbox.indeterminate).toBe(true);
});
});
});
@@ -0,0 +1,100 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Code } from '../Code';
describe('Code 컴포넌트', () => {
it('code 요소가 렌더링된다', () => {
const { container } = render(<Code>const x = 1;</Code>);
const code = container.querySelector('code');
expect(code).toBeTruthy();
expect(code?.textContent).toBe('const x = 1;');
});
it('자식 요소를 렌더링한다', () => {
render(<Code>console.log("Hello");</Code>);
expect(screen.getByText('console.log("Hello");')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Code className="custom-code">코드</Code>);
const code = container.querySelector('code');
expect(code?.className).toContain('custom-code');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<Code onClick={handleClick}>클릭 가능한 코드</Code>);
const code = screen.getByText('클릭 가능한 코드');
fireEvent.click(code);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('id 속성이 적용된다', () => {
const { container } = render(<Code id="code-snippet">snippet</Code>);
const code = container.querySelector('code');
expect(code?.id).toBe('code-snippet');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Code data-testid="test-code">테스트</Code>);
const code = container.querySelector('code');
expect(code?.getAttribute('data-testid')).toBe('test-code');
});
it('style 속성이 적용된다', () => {
const style = { color: 'red', fontSize: '12px' };
const { container } = render(<Code style={style}>styled code</Code>);
const code = container.querySelector('code') as HTMLElement;
expect(code.style.color).toBe('red');
expect(code.style.fontSize).toBe('12px');
});
it('aria 속성이 적용된다', () => {
const { container } = render(<Code aria-label="코드 스니펫">snippet</Code>);
const code = container.querySelector('code');
expect(code?.getAttribute('aria-label')).toBe('코드 스니펫');
});
it('빈 className이어도 렌더링된다', () => {
const { container } = render(<Code>코드</Code>);
const code = container.querySelector('code');
expect(code).toBeTruthy();
expect(code?.className).toBe('');
});
it('여러 줄 코드를 렌더링한다', () => {
const multilineCode = 'const x = 1;\nconst y = 2;';
render(<Code>{multilineCode}</Code>);
expect(screen.getByText(/const x = 1/)).toBeTruthy();
});
it('복합 Props가 함께 적용된다', () => {
const handleClick = vi.fn();
const { container } = render(
<Code
id="main-code"
className="bg-gray-100 text-sm"
style={{ padding: '4px' }}
onClick={handleClick}
data-testid="code-block"
>
npm install
</Code>
);
const code = container.querySelector('code')!;
expect(code.id).toBe('main-code');
expect(code.className).toContain('bg-gray-100');
expect(code.className).toContain('text-sm');
expect((code as HTMLElement).style.padding).toBe('4px');
expect(code.getAttribute('data-testid')).toBe('code-block');
fireEvent.click(code);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('특수 문자가 포함된 코드를 렌더링한다', () => {
render(<Code>{'<div>Hello</div>'}</Code>);
expect(screen.getByText('<div>Hello</div>')).toBeTruthy();
});
});
@@ -0,0 +1,222 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { FileInput } from '../FileInput';
describe('FileInput 컴포넌트', () => {
describe('기본 렌더링', () => {
it('기본 버튼 텍스트와 placeholder가 렌더링된다', () => {
render(<FileInput />);
expect(screen.getByText('Browse')).toBeTruthy();
expect(screen.getByText('No file selected')).toBeTruthy();
});
it('커스텀 버튼 텍스트가 적용된다', () => {
render(<FileInput buttonText="파일 선택" />);
expect(screen.getByText('파일 선택')).toBeTruthy();
});
it('커스텀 placeholder가 적용된다', () => {
render(<FileInput placeholder="파일을 선택하세요" />);
expect(screen.getByText('파일을 선택하세요')).toBeTruthy();
});
it('숨겨진 file input이 렌더링된다', () => {
const { container } = render(<FileInput />);
const fileInput = container.querySelector('input[type="file"]');
expect(fileInput).toBeTruthy();
expect(fileInput?.className).toContain('hidden');
});
});
describe('파일 선택', () => {
it('버튼 클릭 시 file input이 트리거된다', () => {
const { container } = render(<FileInput />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const clickSpy = vi.spyOn(fileInput, 'click');
const button = screen.getByText('Browse');
fireEvent.click(button);
expect(clickSpy).toHaveBeenCalled();
});
it('파일 선택 시 onChange 콜백이 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<FileInput onChange={handleChange} />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test content'], 'test.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(handleChange).toHaveBeenCalledWith(file);
});
it('파일 선택 시 파일명이 표시된다', () => {
const { container } = render(<FileInput />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test content'], 'module.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(screen.getByText('module.zip')).toBeTruthy();
});
});
describe('파일 크기 검증', () => {
it('파일 크기가 maxSize를 초과하면 onError가 호출된다', () => {
const handleError = vi.fn();
const handleChange = vi.fn();
const { container } = render(
<FileInput maxSize={1} onChange={handleChange} onError={handleError} />
);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
// 2MB 파일 생성 (maxSize 1MB 초과)
const largeContent = new ArrayBuffer(2 * 1024 * 1024);
const file = new File([largeContent], 'large.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(handleError).toHaveBeenCalledWith('File size exceeds 1MB limit');
expect(handleChange).not.toHaveBeenCalled();
});
it('파일 크기가 maxSize 이내이면 정상 처리된다', () => {
const handleError = vi.fn();
const handleChange = vi.fn();
const { container } = render(
<FileInput maxSize={5} onChange={handleChange} onError={handleError} />
);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
// 1MB 파일 생성 (maxSize 5MB 이내)
const content = new ArrayBuffer(1 * 1024 * 1024);
const file = new File([content], 'small.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(handleError).not.toHaveBeenCalled();
expect(handleChange).toHaveBeenCalledWith(file);
});
});
describe('파일 초기화', () => {
it('파일 선택 후 클리어 버튼이 표시된다', () => {
const { container } = render(<FileInput />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test'], 'test.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
const clearButton = screen.getByLabelText('Clear file');
expect(clearButton).toBeTruthy();
});
it('클리어 버튼 클릭 시 파일이 초기화된다', () => {
const handleChange = vi.fn();
const { container } = render(<FileInput onChange={handleChange} />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test'], 'test.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
expect(handleChange).toHaveBeenCalledWith(file);
const clearButton = screen.getByLabelText('Clear file');
fireEvent.click(clearButton);
expect(handleChange).toHaveBeenLastCalledWith(null);
expect(screen.getByText('No file selected')).toBeTruthy();
});
});
describe('비활성화 상태', () => {
it('disabled 상태에서 버튼이 비활성화된다', () => {
render(<FileInput disabled />);
const button = screen.getByText('Browse');
expect(button).toHaveProperty('disabled', true);
});
it('disabled 상태에서 file input이 비활성화된다', () => {
const { container } = render(<FileInput disabled />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
expect(fileInput.disabled).toBe(true);
});
it('disabled 상태에서 클리어 버튼이 표시되지 않는다', () => {
const { container } = render(<FileInput disabled />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['test'], 'test.zip', { type: 'application/zip' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
fireEvent.change(fileInput);
const clearButton = screen.queryByLabelText('Clear file');
expect(clearButton).toBeNull();
});
});
describe('accept 속성', () => {
it('accept 속성이 file input에 적용된다', () => {
const { container } = render(<FileInput accept=".zip,.tar.gz" />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
expect(fileInput.accept).toBe('.zip,.tar.gz');
});
});
describe('className 속성', () => {
it('className이 wrapper에 적용된다', () => {
const { container } = render(<FileInput className="custom-class" />);
const wrapper = container.firstChild as HTMLElement;
expect(wrapper.className).toContain('custom-class');
});
});
describe('빈 파일 선택', () => {
it('파일 선택 없이 change 이벤트 발생 시 onChange에 null이 전달된다', () => {
const handleChange = vi.fn();
const { container } = render(<FileInput onChange={handleChange} />);
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(fileInput, 'files', {
value: [],
writable: false,
});
fireEvent.change(fileInput);
expect(handleChange).toHaveBeenCalledWith(null);
});
});
});
@@ -0,0 +1,176 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Form } from '../Form';
describe('Form 컴포넌트', () => {
describe('기본 렌더링', () => {
it('form 요소가 렌더링된다', () => {
const { container } = render(<Form>Form Content</Form>);
const form = container.querySelector('form');
expect(form).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(<Form>Test Form Content</Form>);
expect(screen.getByText('Test Form Content')).toBeTruthy();
});
});
describe('이벤트 핸들링', () => {
it('onSubmit 핸들러가 호출된다', () => {
const handleSubmit = vi.fn((e) => e.preventDefault());
const { container } = render(<Form onSubmit={handleSubmit}>Submit Form</Form>);
const form = container.querySelector('form')!;
fireEvent.submit(form);
expect(handleSubmit).toHaveBeenCalledTimes(1);
});
it('onReset 핸들러가 호출된다', () => {
const handleReset = vi.fn();
const { container } = render(<Form onReset={handleReset}>Reset Form</Form>);
const form = container.querySelector('form')!;
fireEvent.reset(form);
expect(handleReset).toHaveBeenCalledTimes(1);
});
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Form onChange={handleChange}>
<input type="text" name="test" />
</Form>
);
const input = container.querySelector('input')!;
fireEvent.change(input, { target: { value: 'test value' } });
expect(handleChange).toHaveBeenCalled();
});
});
describe('HTML 속성', () => {
it('action 속성이 적용된다', () => {
const { container } = render(<Form action="/submit">Form</Form>);
const form = container.querySelector('form');
expect(form?.action).toContain('/submit');
});
it('method 속성이 적용된다', () => {
const { container } = render(<Form method="post">Form</Form>);
const form = container.querySelector('form');
expect(form?.method).toBe('post');
});
it('encType 속성이 적용된다', () => {
const { container } = render(<Form encType="multipart/form-data">Form</Form>);
const form = container.querySelector('form');
expect(form?.enctype).toBe('multipart/form-data');
});
it('target 속성이 적용된다', () => {
const { container } = render(<Form target="_blank">Form</Form>);
const form = container.querySelector('form');
expect(form?.target).toBe('_blank');
});
it('autoComplete 속성이 적용된다', () => {
const { container } = render(<Form autoComplete="off">Form</Form>);
const form = container.querySelector('form');
expect(form?.getAttribute('autocomplete')).toBe('off');
});
it('noValidate 속성이 적용된다', () => {
const { container } = render(<Form noValidate>Form</Form>);
const form = container.querySelector('form');
expect(form?.noValidate).toBe(true);
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Form className="custom-form">Form</Form>);
const form = container.querySelector('form');
expect(form?.className).toContain('custom-form');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Form id="login-form">Form</Form>);
const form = container.querySelector('form');
expect(form?.id).toBe('login-form');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Form data-testid="test-form">Form</Form>);
const form = container.querySelector('form');
expect(form?.getAttribute('data-testid')).toBe('test-form');
});
it('name 속성이 적용된다', () => {
const { container } = render(<Form name="registration">Form</Form>);
const form = container.querySelector('form');
expect(form?.name).toBe('registration');
});
});
describe('복잡한 Form 구조', () => {
it('여러 input 요소를 포함한다', () => {
const { container } = render(
<Form>
<input type="text" name="username" placeholder="사용자명" />
<input type="password" name="password" placeholder="비밀번호" />
<button type="submit">제출</button>
</Form>
);
expect(screen.getByPlaceholderText('사용자명')).toBeTruthy();
expect(screen.getByPlaceholderText('비밀번호')).toBeTruthy();
expect(screen.getByText('제출')).toBeTruthy();
});
it('중첩된 div와 label을 포함한다', () => {
render(
<Form>
<div>
<label htmlFor="email">이메일</label>
<input type="email" id="email" name="email" />
</div>
</Form>
);
expect(screen.getByLabelText('이메일')).toBeTruthy();
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleSubmit = vi.fn((e) => e.preventDefault());
const { container } = render(
<Form
method="post"
action="/api/submit"
onSubmit={handleSubmit}
className="custom-form"
autoComplete="off"
noValidate
>
<input type="text" name="field" />
<button type="submit">제출</button>
</Form>
);
const form = container.querySelector('form')!;
expect(form.method).toBe('post');
expect(form.action).toContain('/api/submit');
expect(form.className).toContain('custom-form');
expect(form.getAttribute('autocomplete')).toBe('off');
expect(form.noValidate).toBe(true);
fireEvent.submit(form);
expect(handleSubmit).toHaveBeenCalledTimes(1);
});
});
});
@@ -0,0 +1,262 @@
import { describe, it, expect } from 'vitest';
import { render } from '@testing-library/react';
import { Icon } from '../Icon';
import { IconName } from '../IconTypes';
describe('Icon 컴포넌트', () => {
describe('기본 렌더링', () => {
it('아이콘이 렌더링된다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon).toBeTruthy();
});
it('문자열 name prop으로 렌더링된다', () => {
const { container } = render(<Icon name="fa-user" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
});
it('IconName enum으로 렌더링된다', () => {
const { container } = render(<Icon name={IconName.User} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
});
it('기본 iconStyle은 solid이다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fas');
});
});
describe('Icon Style', () => {
it('solid 스타일이 적용된다', () => {
const { container } = render(<Icon name="user" iconStyle="solid" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fas');
});
it('regular 스타일이 적용된다', () => {
const { container } = render(<Icon name="user" iconStyle="regular" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('far');
});
it('light 스타일이 적용된다', () => {
const { container } = render(<Icon name="user" iconStyle="light" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fal');
});
it('duotone 스타일이 적용된다', () => {
const { container } = render(<Icon name="user" iconStyle="duotone" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fad');
});
it('brands 스타일이 적용된다', () => {
const { container } = render(<Icon name="facebook" iconStyle="brands" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fab');
});
});
describe('Icon Size', () => {
it('xs 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="xs" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-xs');
});
it('sm 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="sm" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-sm');
});
it('lg 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="lg" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-lg');
});
it('2x 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="2x" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-2x');
});
it('3x 크기가 적용된다', () => {
const { container } = render(<Icon name="user" size="3x" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-3x');
});
});
describe('Icon Animation', () => {
it('spin 애니메이션이 적용된다', () => {
const { container } = render(<Icon name="spinner" spin />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-spin');
});
it('pulse 애니메이션이 적용된다', () => {
const { container } = render(<Icon name="circle-notch" pulse />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-pulse');
});
it('spin과 pulse가 함께 적용되지 않는다', () => {
const { container } = render(<Icon name="spinner" spin pulse />);
const icon = container.querySelector('i');
// 둘 다 true지만 일반적으로 하나만 사용해야 함
expect(icon?.className).toContain('fa-spin');
expect(icon?.className).toContain('fa-pulse');
});
});
describe('Fixed Width', () => {
it('fixedWidth가 적용된다', () => {
const { container } = render(<Icon name="user" fixedWidth />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-fw');
});
it('fixedWidth가 false일 때 적용되지 않는다', () => {
const { container } = render(<Icon name="user" fixedWidth={false} />);
const icon = container.querySelector('i');
expect(icon?.className).not.toContain('fa-fw');
});
});
describe('Color', () => {
it('color prop이 클래스로 적용된다', () => {
const { container } = render(<Icon name="heart" color="text-red-500" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('text-red-500');
});
it('여러 색상 클래스가 적용된다', () => {
const { container } = render(<Icon name="star" color="text-yellow-400 dark:text-yellow-300" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('text-yellow-400');
expect(icon?.className).toContain('dark:text-yellow-300');
});
});
describe('Accessibility', () => {
it('role="img"가 적용된다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('role')).toBe('img');
});
it('기본 aria-label이 생성된다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('aria-label')).toBe('user');
});
it('하이픈이 공백으로 변환된다', () => {
const { container } = render(<Icon name="shopping-cart" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('aria-label')).toBe('shopping cart');
});
it('사용자 정의 ariaLabel이 적용된다', () => {
const { container } = render(<Icon name="user" ariaLabel="사용자 프로필" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('aria-label')).toBe('사용자 프로필');
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Icon name="user" className="custom-icon" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('custom-icon');
});
it('style prop이 적용된다', () => {
const { container } = render(<Icon name="user" style={{ fontSize: '24px', color: 'red' }} />);
const icon = container.querySelector('i') as HTMLElement;
expect(icon.style.fontSize).toBe('24px');
expect(icon.style.color).toBe('red');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Icon name="user" data-testid="test-icon" />);
const icon = container.querySelector('i');
expect(icon?.getAttribute('data-testid')).toBe('test-icon');
});
});
describe('IconName enum 사용', () => {
it('User 아이콘이 렌더링된다', () => {
const { container } = render(<Icon name={IconName.User} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
});
it('Search 아이콘이 렌더링된다', () => {
const { container } = render(<Icon name={IconName.Search} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-search');
});
it('ShoppingCart 아이콘이 렌더링된다', () => {
const { container } = render(<Icon name={IconName.ShoppingCart} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-shopping-cart');
});
it('Heart 아이콘이 렌더링된다', () => {
const { container } = render(<Icon name={IconName.Heart} />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-heart');
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const { container } = render(
<Icon
name={IconName.Spinner}
iconStyle="solid"
size="2x"
color="text-blue-500"
spin
fixedWidth
ariaLabel="로딩 중"
className="custom-spinner"
/>
);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fas');
expect(icon?.className).toContain('fa-spinner');
expect(icon?.className).toContain('fa-2x');
expect(icon?.className).toContain('text-blue-500');
expect(icon?.className).toContain('fa-spin');
expect(icon?.className).toContain('fa-fw');
expect(icon?.className).toContain('custom-spinner');
expect(icon?.getAttribute('aria-label')).toBe('로딩 중');
});
});
describe('아이콘 이름 처리', () => {
it('fa- 접두사가 있는 경우 중복 제거된다', () => {
const { container } = render(<Icon name="fa-user" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
expect(icon?.className).not.toContain('fa-fa-user');
});
it('fa- 접두사가 없는 경우 자동 추가된다', () => {
const { container } = render(<Icon name="user" />);
const icon = container.querySelector('i');
expect(icon?.className).toContain('fa-user');
});
});
});
@@ -0,0 +1,462 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Input } from '../Input';
describe('Input 컴포넌트', () => {
describe('기본 렌더링', () => {
it('input 요소가 렌더링된다', () => {
const { container } = render(<Input />);
const input = container.querySelector('input');
expect(input).toBeTruthy();
});
it('placeholder가 표시된다', () => {
render(<Input placeholder="이름을 입력하세요" />);
expect(screen.getByPlaceholderText('이름을 입력하세요')).toBeTruthy();
});
it('value가 설정된다', () => {
const { container } = render(<Input value="테스트 값" onChange={() => {}} />);
const input = container.querySelector('input') as HTMLInputElement;
expect(input.value).toBe('테스트 값');
});
});
describe('Input Type', () => {
it('text type이 적용된다', () => {
const { container } = render(<Input type="text" />);
const input = container.querySelector('input');
expect(input?.type).toBe('text');
});
it('password type이 적용된다', () => {
const { container } = render(<Input type="password" />);
const input = container.querySelector('input');
expect(input?.type).toBe('password');
});
it('email type이 적용된다', () => {
const { container } = render(<Input type="email" />);
const input = container.querySelector('input');
expect(input?.type).toBe('email');
});
it('number type이 적용된다', () => {
const { container } = render(<Input type="number" />);
const input = container.querySelector('input');
expect(input?.type).toBe('number');
});
it('tel type이 적용된다', () => {
const { container } = render(<Input type="tel" />);
const input = container.querySelector('input');
expect(input?.type).toBe('tel');
});
it('url type이 적용된다', () => {
const { container } = render(<Input type="url" />);
const input = container.querySelector('input');
expect(input?.type).toBe('url');
});
it('date type이 적용된다', () => {
const { container } = render(<Input type="date" />);
const input = container.querySelector('input');
expect(input?.type).toBe('date');
});
});
describe('이벤트 핸들링', () => {
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input onChange={handleChange} />);
const input = container.querySelector('input')!;
fireEvent.change(input, { target: { value: '새 값' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
it('onFocus 핸들러가 호출된다', () => {
const handleFocus = vi.fn();
const { container } = render(<Input onFocus={handleFocus} />);
const input = container.querySelector('input')!;
fireEvent.focus(input);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
it('onBlur 핸들러가 호출된다', () => {
const handleBlur = vi.fn();
const { container } = render(<Input onBlur={handleBlur} />);
const input = container.querySelector('input')!;
fireEvent.blur(input);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
it('onKeyDown 핸들러가 호출된다', () => {
const handleKeyDown = vi.fn();
const { container } = render(<Input onKeyDown={handleKeyDown} />);
const input = container.querySelector('input')!;
fireEvent.keyDown(input, { key: 'Enter' });
expect(handleKeyDown).toHaveBeenCalledTimes(1);
});
});
describe('HTML 속성', () => {
it('disabled 속성이 적용된다', () => {
const { container } = render(<Input disabled />);
const input = container.querySelector('input');
expect(input?.disabled).toBe(true);
});
it('readonly 속성이 적용된다', () => {
const { container } = render(<Input readOnly />);
const input = container.querySelector('input');
expect(input?.readOnly).toBe(true);
});
it('required 속성이 적용된다', () => {
const { container } = render(<Input required />);
const input = container.querySelector('input');
expect(input?.required).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(<Input name="username" />);
const input = container.querySelector('input');
expect(input?.name).toBe('username');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Input id="email-input" />);
const input = container.querySelector('input');
expect(input?.id).toBe('email-input');
});
it('maxLength 속성이 적용된다', () => {
const { container } = render(<Input maxLength={10} />);
const input = container.querySelector('input');
expect(input?.maxLength).toBe(10);
});
it('minLength 속성이 적용된다', () => {
const { container } = render(<Input minLength={3} />);
const input = container.querySelector('input');
expect(input?.minLength).toBe(3);
});
it('pattern 속성이 적용된다', () => {
const { container } = render(<Input pattern="[0-9]{3}-[0-9]{4}" />);
const input = container.querySelector('input');
expect(input?.pattern).toBe('[0-9]{3}-[0-9]{4}');
});
});
describe('Label 및 Error Props', () => {
it('label prop이 존재한다', () => {
// label prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Input label="사용자 이름" />);
const input = container.querySelector('input');
expect(input).toBeTruthy();
});
it('error prop이 존재한다', () => {
// error prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Input error="필수 입력 항목입니다" />);
const input = container.querySelector('input');
expect(input).toBeTruthy();
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Input className="custom-input" />);
const input = container.querySelector('input');
expect(input?.className).toContain('custom-input');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Input aria-label="이메일 입력" />);
const input = container.querySelector('input');
expect(input?.getAttribute('aria-label')).toBe('이메일 입력');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Input data-testid="test-input" />);
const input = container.querySelector('input');
expect(input?.getAttribute('data-testid')).toBe('test-input');
});
it('autoComplete 속성이 적용된다', () => {
const { container } = render(<Input autoComplete="off" />);
const input = container.querySelector('input');
expect(input?.getAttribute('autocomplete')).toBe('off');
});
// autoFocus는 jsdom 환경에서 제대로 테스트되지 않으므로 생략
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Input
type="email"
name="email"
placeholder="이메일을 입력하세요"
required
className="custom-input"
onChange={handleChange}
/>
);
const input = container.querySelector('input')!;
expect(input.type).toBe('email');
expect(input.name).toBe('email');
expect(input.placeholder).toBe('이메일을 입력하세요');
expect(input.required).toBe(true);
expect(input.className).toContain('custom-input');
fireEvent.change(input, { target: { value: 'test@example.com' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
describe('IME 조합 처리 (한글 입력)', () => {
it('IME 조합 중에는 onChange가 호출되지 않는다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')!;
// IME 조합 시작
fireEvent.compositionStart(input);
// 조합 중 입력 (한글 'ㄱ' -> '가' -> '간')
fireEvent.change(input, { target: { value: 'ㄱ' } });
fireEvent.change(input, { target: { value: '가' } });
fireEvent.change(input, { target: { value: '간' } });
// IME 조합 중에는 onChange가 호출되지 않아야 함
expect(handleChange).not.toHaveBeenCalled();
});
it('IME 조합 완료 후 onChange가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')! as HTMLInputElement;
// IME 조합 시작
fireEvent.compositionStart(input);
// 조합 중 입력 - input의 실제 value를 설정
Object.defineProperty(input, 'value', { value: '한글', writable: true });
fireEvent.change(input, { target: { value: '한글' } });
// IME 조합 완료
fireEvent.compositionEnd(input);
// 조합 완료 후 onChange가 호출되어야 함
expect(handleChange).toHaveBeenCalledTimes(1);
// onChange에 전달된 이벤트의 target.value가 '한글'이어야 함
expect(handleChange.mock.calls[0][0].target.value).toBe('한글');
});
it('IME 조합 중에도 화면에 입력이 표시된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')! as HTMLInputElement;
// IME 조합 시작
fireEvent.compositionStart(input);
// 조합 중 입력
fireEvent.change(input, { target: { value: '테스트' } });
// 화면에는 입력이 표시되어야 함 (로컬 상태)
expect(input.value).toBe('테스트');
});
it('영문 입력 시 onChange가 즉시 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')!;
// 영문 입력 (IME 조합 없음)
fireEvent.change(input, { target: { value: 'a' } });
// 즉시 onChange가 호출되어야 함
expect(handleChange).toHaveBeenCalledTimes(1);
});
// TODO: IME 테스트는 happy-dom 환경에서 composition 이벤트가 실제 브라우저처럼 동작하지 않아 건너뜀
it.skip('IME 조합 후 영문 입력 시 onChange가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Input value="" onChange={handleChange} />);
const input = container.querySelector('input')! as HTMLInputElement;
// IME 조합 시작 및 완료
fireEvent.compositionStart(input);
Object.defineProperty(input, 'value', { value: '한', writable: true });
fireEvent.change(input, { target: { value: '한' } });
fireEvent.compositionEnd(input);
// 한글 조합 완료로 1회
expect(handleChange).toHaveBeenCalledTimes(1);
// 영문 입력
fireEvent.change(input, { target: { value: '한a' } });
// 영문 입력으로 추가 1회
expect(handleChange).toHaveBeenCalledTimes(2);
});
it('외부 value prop이 변경되면 로컬 값도 동기화된다', async () => {
const handleChange = vi.fn();
const { container, rerender } = render(
<Input value="초기값" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
expect(input.value).toBe('초기값');
// 외부에서 value 변경
rerender(<Input value="변경된값" onChange={handleChange} />);
await waitFor(() => {
expect(input.value).toBe('변경된값');
});
});
it('포커스 상태에서 외부 value prop 변경 시 로컬 값이 동기화되지 않는다 (플리커 방지)', async () => {
const handleChange = vi.fn();
const { container, rerender } = render(
<Input value="2000" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
expect(input.value).toBe('2000');
// 사용자가 Input에 포커스 (입력 중 상태)
input.focus();
expect(document.activeElement).toBe(input);
// 사용자 입력으로 로컬 값 변경
fireEvent.change(input, { target: { value: '30000' } });
expect(input.value).toBe('30000');
// 부모 리렌더링으로 stale value prop 전달 (debounce 대기 중 발생하는 시나리오)
rerender(<Input value="2000" onChange={handleChange} />);
// 포커스 상태이므로 stale value로 동기화되지 않아야 함
await waitFor(() => {
expect(input.value).toBe('30000');
});
});
it('포커스 해제 후 외부 value prop 변경 시 로컬 값이 정상 동기화된다', async () => {
const handleChange = vi.fn();
const { container, rerender } = render(
<Input value="초기값" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
// 포커스 후 해제
input.focus();
input.blur();
expect(document.activeElement).not.toBe(input);
// 외부에서 value 변경
rerender(<Input value="새값" onChange={handleChange} />);
// 포커스 해제 상태이므로 정상 동기화
await waitFor(() => {
expect(input.value).toBe('새값');
});
});
it('포커스 상태에서 연속 입력 시 마지막 입력값이 유지된다', async () => {
const handleChange = vi.fn();
const { container, rerender } = render(
<Input value="100" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
input.focus();
// 연속 입력 (100 → 1000 → 10000 → 100000)
fireEvent.change(input, { target: { value: '1000' } });
fireEvent.change(input, { target: { value: '10000' } });
fireEvent.change(input, { target: { value: '100000' } });
// 중간에 stale value로 리렌더링
rerender(<Input value="100" onChange={handleChange} />);
// 마지막 입력값 유지
await waitFor(() => {
expect(input.value).toBe('100000');
});
});
it('defaultValue로 초기값이 설정된다', () => {
const { container } = render(<Input defaultValue="기본값" />);
const input = container.querySelector('input')! as HTMLInputElement;
expect(input.value).toBe('기본값');
});
it('value 없이 defaultValue만 있으면 uncontrolled로 동작한다', () => {
const handleChange = vi.fn();
const { container } = render(
<Input defaultValue="기본값" onChange={handleChange} />
);
const input = container.querySelector('input')! as HTMLInputElement;
// 직접 입력
fireEvent.change(input, { target: { value: '새값' } });
// onChange가 호출되어야 함
expect(handleChange).toHaveBeenCalledTimes(1);
});
// TODO: IME 테스트는 happy-dom 환경에서 composition 이벤트가 실제 브라우저처럼 동작하지 않아 건너뜀
// 실제 브라우저 환경에서 E2E 테스트로 검증 필요
it.skip('IME 조합 중에는 onKeyPress가 호출되지 않는다', () => {
const handleKeyPress = vi.fn();
const { container } = render(<Input value="" onChange={() => {}} onKeyPress={handleKeyPress} />);
const input = container.querySelector('input')!;
// IME 조합 시작
fireEvent.compositionStart(input);
// 조합 중 Enter 키
fireEvent.keyPress(input, { key: 'Enter' });
// IME 조합 중에는 onKeyPress가 호출되지 않아야 함
expect(handleKeyPress).not.toHaveBeenCalled();
});
// TODO: IME 테스트는 happy-dom 환경에서 composition 이벤트가 실제 브라우저처럼 동작하지 않아 건너뜀
it.skip('IME 조합 완료 후 onKeyPress가 호출된다', () => {
const handleKeyPress = vi.fn();
const { container } = render(<Input value="" onChange={() => {}} onKeyPress={handleKeyPress} />);
const input = container.querySelector('input')!;
// IME 조합 시작 및 완료
fireEvent.compositionStart(input);
fireEvent.compositionEnd(input);
// Enter 키
fireEvent.keyPress(input, { key: 'Enter' });
// 조합 완료 후 onKeyPress가 호출되어야 함
expect(handleKeyPress).toHaveBeenCalledTimes(1);
});
});
});
@@ -0,0 +1,502 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { A } from '../A';
import { Ul } from '../Ul';
import { Li } from '../Li';
import { Nav } from '../Nav';
import { Section } from '../Section';
import { Div } from '../Div';
import { Img } from '../Img';
import { Svg } from '../Svg';
import { Hr } from '../Hr';
describe('기타 컴포넌트', () => {
describe('A (링크) 컴포넌트', () => {
it('a 요소가 렌더링된다', () => {
const { container } = render(<A href="/test">링크 텍스트</A>);
const a = container.querySelector('a');
expect(a).toBeTruthy();
expect(a?.href).toContain('/test');
});
it('자식 요소를 렌더링한다', () => {
render(<A href="#">클릭하세요</A>);
expect(screen.getByText('클릭하세요')).toBeTruthy();
});
it('href 속성이 적용된다', () => {
const { container } = render(<A href="https://example.com">외부 링크</A>);
const a = container.querySelector('a');
expect(a?.href).toBe('https://example.com/');
});
it('target 속성이 적용된다', () => {
const { container } = render(
<A href="/page" target="_blank">
새 탭에서 열기
</A>
);
const a = container.querySelector('a');
expect(a?.target).toBe('_blank');
});
it('rel 속성이 적용된다', () => {
const { container } = render(
<A href="https://external.com" rel="noopener noreferrer">
외부 링크
</A>
);
const a = container.querySelector('a');
expect(a?.rel).toBe('noopener noreferrer');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn((e) => e.preventDefault());
render(
<A href="#" onClick={handleClick}>
클릭 가능한 링크
</A>
);
const a = screen.getByText('클릭 가능한 링크');
fireEvent.click(a);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<A href="#" className="custom-link">
링크
</A>
);
const a = container.querySelector('a');
expect(a?.className).toContain('custom-link');
});
it('download 속성이 적용된다', () => {
const { container } = render(
<A href="/file.pdf" download="document.pdf">
다운로드
</A>
);
const a = container.querySelector('a');
expect(a?.download).toBe('document.pdf');
});
});
describe('Ul (순서없는 목록) 컴포넌트', () => {
it('ul 요소가 렌더링된다', () => {
const { container } = render(
<Ul>
<li>항목</li>
</Ul>
);
const ul = container.querySelector('ul');
expect(ul).toBeTruthy();
});
it('자식 li 요소를 렌더링한다', () => {
render(
<Ul>
<li>항목 1</li>
<li>항목 2</li>
</Ul>
);
expect(screen.getByText('항목 1')).toBeTruthy();
expect(screen.getByText('항목 2')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Ul className="custom-ul">
<li>항목</li>
</Ul>
);
const ul = container.querySelector('ul');
expect(ul?.className).toContain('custom-ul');
});
});
describe('Li (목록 항목) 컴포넌트', () => {
it('li 요소가 렌더링된다', () => {
const { container } = render(
<ul>
<Li>목록 항목</Li>
</ul>
);
const li = container.querySelector('li');
expect(li).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<ul>
<Li>테스트 항목</Li>
</ul>
);
expect(screen.getByText('테스트 항목')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<ul>
<Li className="custom-li">항목</Li>
</ul>
);
const li = container.querySelector('li');
expect(li?.className).toContain('custom-li');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(
<ul>
<Li onClick={handleClick}>클릭 가능한 항목</Li>
</ul>
);
const li = screen.getByText('클릭 가능한 항목');
fireEvent.click(li);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
describe('Nav (네비게이션) 컴포넌트', () => {
it('nav 요소가 렌더링된다', () => {
const { container } = render(
<Nav>
<a href="/">홈</a>
</Nav>
);
const nav = container.querySelector('nav');
expect(nav).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<Nav>
<ul>
<li>메뉴 1</li>
<li>메뉴 2</li>
</ul>
</Nav>
);
expect(screen.getByText('메뉴 1')).toBeTruthy();
expect(screen.getByText('메뉴 2')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Nav className="main-nav">
<ul>
<li>메뉴</li>
</ul>
</Nav>
);
const nav = container.querySelector('nav');
expect(nav?.className).toContain('main-nav');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Nav aria-label="주 메뉴">내용</Nav>);
const nav = container.querySelector('nav');
expect(nav?.getAttribute('aria-label')).toBe('주 메뉴');
});
});
describe('Section 컴포넌트', () => {
it('section 요소가 렌더링된다', () => {
const { container } = render(<Section>섹션 내용</Section>);
const section = container.querySelector('section');
expect(section).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<Section>
<h2>섹션 제목</h2>
<p>섹션 내용</p>
</Section>
);
expect(screen.getByText('섹션 제목')).toBeTruthy();
expect(screen.getByText('섹션 내용')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Section className="custom-section">내용</Section>);
const section = container.querySelector('section');
expect(section?.className).toContain('custom-section');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Section id="about">소개</Section>);
const section = container.querySelector('section');
expect(section?.id).toBe('about');
});
});
describe('Div 컴포넌트', () => {
it('div 요소가 렌더링된다', () => {
const { container } = render(<Div>div 내용</Div>);
const div = container.querySelector('div');
expect(div).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(<Div>테스트 내용</Div>);
expect(screen.getByText('테스트 내용')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Div className="container mx-auto">내용</Div>);
const div = container.querySelector('div');
expect(div?.className).toContain('container');
expect(div?.className).toContain('mx-auto');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<Div onClick={handleClick}>클릭 가능한 div</Div>);
const div = screen.getByText('클릭 가능한 div');
fireEvent.click(div);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('style 속성이 적용된다', () => {
const { container } = render(
<Div style={{ padding: '20px', backgroundColor: 'blue' }}>내용</Div>
);
const div = container.querySelector('div') as HTMLElement;
expect(div.style.padding).toBe('20px');
expect(div.style.backgroundColor).toBe('blue');
});
it('중첩된 div가 렌더링된다', () => {
const { container } = render(
<Div className="outer">
<Div className="inner">중첩된 내용</Div>
</Div>
);
const outerDiv = container.querySelector('.outer');
const innerDiv = container.querySelector('.inner');
expect(outerDiv).toBeTruthy();
expect(innerDiv).toBeTruthy();
});
});
describe('Img 컴포넌트', () => {
it('img 요소가 렌더링된다', () => {
const { container } = render(<Img src="/test.jpg" alt="테스트 이미지" />);
const img = container.querySelector('img');
expect(img).toBeTruthy();
});
it('src 속성이 적용된다', () => {
const { container } = render(<Img src="/image.png" alt="이미지" />);
const img = container.querySelector('img');
expect(img?.src).toContain('/image.png');
});
it('alt 속성이 적용된다', () => {
const { container } = render(<Img src="/test.jpg" alt="설명 텍스트" />);
const img = container.querySelector('img');
expect(img?.alt).toBe('설명 텍스트');
});
it('기본 alt는 빈 문자열이다', () => {
const { container } = render(<Img src="/test.jpg" />);
const img = container.querySelector('img');
expect(img?.alt).toBe('');
});
it('width와 height 속성이 적용된다', () => {
const { container } = render(<Img src="/test.jpg" alt="이미지" width={200} height={150} />);
const img = container.querySelector('img');
expect(img?.width).toBe(200);
expect(img?.height).toBe(150);
});
it('loading 속성이 적용된다', () => {
const { container } = render(<Img src="/test.jpg" alt="이미지" loading="lazy" />);
const img = container.querySelector('img');
expect(img?.getAttribute('loading')).toBe('lazy');
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Img src="/test.jpg" alt="이미지" className="rounded-lg" />);
const img = container.querySelector('img');
expect(img?.className).toContain('rounded-lg');
});
it('onLoad 이벤트가 작동한다', () => {
const handleLoad = vi.fn();
const { container } = render(<Img src="/test.jpg" alt="이미지" onLoad={handleLoad} />);
const img = container.querySelector('img')!;
fireEvent.load(img);
expect(handleLoad).toHaveBeenCalledTimes(1);
});
it('onError 이벤트가 작동한다', () => {
const handleError = vi.fn();
const { container } = render(<Img src="/invalid.jpg" alt="이미지" onError={handleError} />);
const img = container.querySelector('img')!;
fireEvent.error(img);
expect(handleError).toHaveBeenCalledTimes(1);
});
});
describe('Svg 컴포넌트', () => {
it('svg 요소가 렌더링된다', () => {
const { container } = render(
<Svg viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg).toBeTruthy();
});
it('viewBox 속성이 적용된다', () => {
const { container } = render(
<Svg viewBox="0 0 100 100">
<rect x="0" y="0" width="100" height="100" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.getAttribute('viewBox')).toBe('0 0 100 100');
});
it('width와 height 속성이 적용된다', () => {
const { container } = render(
<Svg width="24" height="24">
<path d="M0 0h24v24H0z" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.getAttribute('width')).toBe('24');
expect(svg?.getAttribute('height')).toBe('24');
});
it('자식 요소를 렌더링한다', () => {
const { container } = render(
<Svg viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" fill="blue" />
<rect x="5" y="5" width="14" height="14" fill="red" />
</Svg>
);
const svg = container.querySelector('svg');
const circle = svg?.querySelector('circle');
const rect = svg?.querySelector('rect');
expect(circle).toBeTruthy();
expect(rect).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Svg className="icon icon-lg" viewBox="0 0 24 24">
<path d="M0 0h24v24H0z" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.className.baseVal).toContain('icon');
expect(svg?.className.baseVal).toContain('icon-lg');
});
it('fill과 stroke 속성이 적용된다', () => {
const { container } = render(
<Svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
<circle cx="12" cy="12" r="10" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.getAttribute('fill')).toBe('none');
expect(svg?.getAttribute('stroke')).toBe('currentColor');
});
it('aria 속성이 적용된다', () => {
const { container } = render(
<Svg viewBox="0 0 24 24" aria-label="아이콘 설명" role="img">
<path d="M0 0h24v24H0z" />
</Svg>
);
const svg = container.querySelector('svg');
expect(svg?.getAttribute('aria-label')).toBe('아이콘 설명');
expect(svg?.getAttribute('role')).toBe('img');
});
});
describe('복합 사용 사례', () => {
it('Nav 안에 Ul과 Li가 중첩된다', () => {
render(
<Nav>
<Ul>
<Li>
<A href="/">홈</A>
</Li>
<Li>
<A href="/about">소개</A>
</Li>
</Ul>
</Nav>
);
expect(screen.getByText('홈')).toBeTruthy();
expect(screen.getByText('소개')).toBeTruthy();
});
it('Section 안에 여러 컴포넌트가 중첩된다', () => {
render(
<Section>
<Div className="header">
<h2>섹션 제목</h2>
</Div>
<Div className="content">
<p>내용</p>
<Ul>
<Li>항목 1</Li>
<Li>항목 2</Li>
</Ul>
</Div>
</Section>
);
expect(screen.getByText('섹션 제목')).toBeTruthy();
expect(screen.getByText('항목 1')).toBeTruthy();
});
it('Div 안에 Img와 텍스트가 함께 렌더링된다', () => {
const { container } = render(
<Div className="card">
<Img src="/product.jpg" alt="상품 이미지" className="card-image" />
<Div className="card-body">
<h3>상품명</h3>
<p>상품 설명</p>
</Div>
</Div>
);
const img = container.querySelector('img');
expect(img?.src).toContain('/product.jpg');
expect(screen.getByText('상품명')).toBeTruthy();
});
});
describe('Hr (수평선) 컴포넌트', () => {
it('hr 요소가 렌더링된다', () => {
const { container } = render(<Hr />);
const hr = container.querySelector('hr');
expect(hr).toBeTruthy();
});
it('className이 적용된다', () => {
const { container } = render(<Hr className="border-gray-100 dark:border-gray-800 mb-4" />);
const hr = container.querySelector('hr');
expect(hr?.className).toContain('border-gray-100');
expect(hr?.className).toContain('dark:border-gray-800');
});
it('추가 HTML 속성이 전달된다', () => {
const { container } = render(<Hr data-testid="divider" />);
const hr = container.querySelector('hr');
expect(hr?.getAttribute('data-testid')).toBe('divider');
});
});
});
@@ -0,0 +1,617 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import React from 'react';
import { Select } from '../Select';
describe('Select 컴포넌트', () => {
describe('기본 렌더링 (children 모드)', () => {
it('select 요소가 렌더링된다', () => {
const { container } = render(
<Select>
<option value="">선택</option>
</Select>
);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
it('option 요소가 렌더링된다', () => {
render(
<Select>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
expect(screen.getByText('옵션 1')).toBeTruthy();
expect(screen.getByText('옵션 2')).toBeTruthy();
});
it('기본 선택 옵션이 표시된다', () => {
const { container } = render(
<Select defaultValue="2">
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select') as HTMLSelectElement;
expect(select.value).toBe('2');
});
});
describe('이벤트 핸들링 (children 모드)', () => {
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Select onChange={handleChange}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select')!;
fireEvent.change(select, { target: { value: '2' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
it('onFocus 핸들러가 호출된다', () => {
const handleFocus = vi.fn();
const { container } = render(
<Select onFocus={handleFocus}>
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select')!;
fireEvent.focus(select);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
it('onBlur 핸들러가 호출된다', () => {
const handleBlur = vi.fn();
const { container } = render(
<Select onBlur={handleBlur}>
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select')!;
fireEvent.blur(select);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
});
describe('value 및 제어 컴포넌트 (children 모드)', () => {
it('value prop이 적용된다', () => {
const { container } = render(
<Select value="2" onChange={() => {}}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
<option value="3">옵션 3</option>
</Select>
);
const select = container.querySelector('select') as HTMLSelectElement;
expect(select.value).toBe('2');
});
it('제어 컴포넌트로 작동한다', () => {
const TestComponent = () => {
const [value, setValue] = React.useState('1');
return (
<Select value={value} onChange={(e) => setValue(String(e.target.value))}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
};
const { container } = render(<TestComponent />);
const select = container.querySelector('select')!;
expect((select as HTMLSelectElement).value).toBe('1');
fireEvent.change(select, { target: { value: '2' } });
expect((select as HTMLSelectElement).value).toBe('2');
});
});
describe('HTML 속성 (children 모드)', () => {
it('disabled 속성이 적용된다', () => {
const { container } = render(
<Select disabled>
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.disabled).toBe(true);
});
it('required 속성이 적용된다', () => {
const { container } = render(
<Select required>
<option value="">선택</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.required).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(
<Select name="category">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.name).toBe('category');
});
it('id 속성이 적용된다', () => {
const { container } = render(
<Select id="category-select">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.id).toBe('category-select');
});
it('multiple 속성이 적용된다', () => {
const { container } = render(
<Select multiple>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.multiple).toBe(true);
});
it('size 속성이 적용된다', () => {
const { container } = render(
<Select size={3}>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.size).toBe(3);
});
});
describe('Label 및 Error Props', () => {
it('label prop이 존재한다', () => {
// label prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(
<Select label="카테고리 선택">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
it('error prop이 존재한다', () => {
// error prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(
<Select error="카테고리를 선택해주세요">
<option value="">선택</option>
</Select>
);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
});
describe('사용자 정의 Props (children 모드)', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Select className="custom-select">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.className).toContain('custom-select');
});
it('aria-label이 적용된다', () => {
const { container } = render(
<Select aria-label="카테고리 선택">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.getAttribute('aria-label')).toBe('카테고리 선택');
});
it('data 속성이 적용된다', () => {
const { container } = render(
<Select data-testid="test-select">
<option value="1">옵션 1</option>
</Select>
);
const select = container.querySelector('select');
expect(select?.getAttribute('data-testid')).toBe('test-select');
});
});
describe('optgroup 지원', () => {
it('optgroup이 렌더링된다', () => {
render(
<Select>
<optgroup label="그룹 1">
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
</optgroup>
<optgroup label="그룹 2">
<option value="3">옵션 3</option>
<option value="4">옵션 4</option>
</optgroup>
</Select>
);
expect(screen.getByText('옵션 1')).toBeTruthy();
expect(screen.getByText('옵션 3')).toBeTruthy();
});
});
describe('복합 Props (children 모드)', () => {
it('여러 props가 함께 적용된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Select
name="category"
value="2"
onChange={handleChange}
required
className="custom-select"
aria-label="카테고리 선택"
>
<option value="">선택하세요</option>
<option value="1">옵션 1</option>
<option value="2">옵션 2</option>
<option value="3">옵션 3</option>
</Select>
);
const select = container.querySelector('select')!;
expect(select.name).toBe('category');
expect((select as HTMLSelectElement).value).toBe('2');
expect(select.required).toBe(true);
expect(select.className).toContain('custom-select');
expect(select.getAttribute('aria-label')).toBe('카테고리 선택');
fireEvent.change(select, { target: { value: '3' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
// ========================================
// 커스텀 드롭다운 모드 (options prop 사용)
// ========================================
describe('커스텀 드롭다운 렌더링 (options 모드)', () => {
const options = [
{ value: '', label: '전체' },
{ value: 'name', label: '이름' },
{ value: 'email', label: '이메일' },
];
it('options prop으로 커스텀 드롭다운이 렌더링된다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
// 버튼이 렌더링되어야 함 (select가 아닌 button)
const button = screen.getByRole('button');
expect(button).toBeTruthy();
});
it('선택된 옵션의 라벨이 버튼에 표시된다', () => {
render(<Select options={options} value="name" onChange={() => {}} />);
expect(screen.getByText('이름')).toBeTruthy();
});
it('빈 값일 때 해당 옵션의 라벨이 표시된다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
expect(screen.getByText('전체')).toBeTruthy();
});
it('버튼 클릭 시 드롭다운이 열린다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
// 드롭다운 메뉴가 열림 (listbox)
const listbox = screen.getByRole('listbox');
expect(listbox).toBeTruthy();
// 모든 옵션이 표시됨 (옵션은 role="option"으로 찾음)
const optionElements = screen.getAllByRole('option');
expect(optionElements.length).toBe(3);
});
it('옵션 클릭 시 onChange가 호출되고 드롭다운이 닫힌다', () => {
const handleChange = vi.fn();
render(<Select options={options} value="" onChange={handleChange} />);
// 드롭다운 열기
const button = screen.getByRole('button');
fireEvent.click(button);
// 옵션 선택
const nameOption = screen.getAllByRole('option').find(
opt => opt.textContent?.includes('이름')
);
fireEvent.click(nameOption!);
// onChange가 호출됨 (synthetic event 형식)
expect(handleChange).toHaveBeenCalledTimes(1);
expect(handleChange).toHaveBeenCalledWith(
expect.objectContaining({
target: { value: 'name' },
type: 'change',
})
);
// 드롭다운이 닫힘
expect(screen.queryByRole('listbox')).toBeNull();
});
it('선택된 옵션에 체크마크가 표시된다', () => {
render(<Select options={options} value="email" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
// 선택된 옵션 찾기
const selectedOption = screen.getAllByRole('option').find(
opt => opt.getAttribute('aria-selected') === 'true'
);
expect(selectedOption).toBeTruthy();
expect(selectedOption?.textContent).toContain('이메일');
});
it('disabled 상태에서 클릭이 작동하지 않는다', () => {
render(<Select options={options} value="" onChange={() => {}} disabled />);
const button = screen.getByRole('button');
expect(button).toHaveProperty('disabled', true);
fireEvent.click(button);
// 드롭다운이 열리지 않음
expect(screen.queryByRole('listbox')).toBeNull();
});
it('외부 클릭 시 드롭다운이 닫힌다', () => {
render(
<div>
<Select options={options} value="" onChange={() => {}} />
<div data-testid="outside">외부 영역</div>
</div>
);
// 드롭다운 열기
const button = screen.getByRole('button');
fireEvent.click(button);
expect(screen.getByRole('listbox')).toBeTruthy();
// 외부 클릭
const outside = screen.getByTestId('outside');
fireEvent.mouseDown(outside);
// 드롭다운이 닫힘
expect(screen.queryByRole('listbox')).toBeNull();
});
it('ESC 키로 드롭다운이 닫힌다', () => {
render(<Select options={options} value="" onChange={() => {}} />);
// 드롭다운 열기
const button = screen.getByRole('button');
fireEvent.click(button);
expect(screen.getByRole('listbox')).toBeTruthy();
// ESC 키 입력
fireEvent.keyDown(document, { key: 'Escape' });
// 드롭다운이 닫힘
expect(screen.queryByRole('listbox')).toBeNull();
});
});
describe('커스텀 드롭다운 스타일 (options 모드)', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2' },
];
it('기본 스타일이 적용된다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button.className).toContain('bg-gray-100');
expect(button.className).toContain('rounded-xl');
});
it('커스텀 className이 적용된다', () => {
render(
<Select
options={options}
value="1"
onChange={() => {}}
className="bg-blue-100 custom-class"
/>
);
const button = screen.getByRole('button');
expect(button.className).toContain('bg-blue-100');
expect(button.className).toContain('custom-class');
});
it('드롭다운 메뉴가 둥근 모서리를 가진다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const listbox = screen.getByRole('listbox');
expect(listbox.className).toContain('rounded-2xl');
expect(listbox.className).toContain('shadow-lg');
});
});
describe('string[] options 지원', () => {
it('string 배열을 옵션으로 변환한다', () => {
render(<Select options={['ko', 'en']} value="ko" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
// 로케일 이름으로 변환됨 (role="option"으로 찾음)
const optionElements = screen.getAllByRole('option');
const labels = optionElements.map(opt => opt.textContent);
expect(labels).toContain('한국어');
expect(labels).toContain('English');
});
it('알 수 없는 로케일은 그대로 표시된다', () => {
render(<Select options={['unknown']} value="unknown" onChange={() => {}} />);
expect(screen.getByText('unknown')).toBeTruthy();
});
});
describe('disabled 옵션 지원', () => {
it('disabled 옵션이 비활성화된다', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2', disabled: true },
];
const handleChange = vi.fn();
render(<Select options={options} value="1" onChange={handleChange} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const disabledOption = screen.getAllByRole('option').find(
opt => opt.textContent?.includes('옵션 2')
);
expect(disabledOption).toHaveProperty('disabled', true);
// 클릭해도 onChange가 호출되지 않음
fireEvent.click(disabledOption!);
expect(handleChange).not.toHaveBeenCalled();
});
});
describe('접근성 (options 모드)', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2' },
];
it('aria-haspopup 속성이 있다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button.getAttribute('aria-haspopup')).toBe('listbox');
});
it('aria-expanded가 열림 상태를 반영한다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button.getAttribute('aria-expanded')).toBe('false');
fireEvent.click(button);
expect(button.getAttribute('aria-expanded')).toBe('true');
});
it('옵션에 role="option"이 있다', () => {
render(<Select options={options} value="1" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const optionElements = screen.getAllByRole('option');
expect(optionElements.length).toBe(2);
});
it('선택된 옵션에 aria-selected="true"가 있다', () => {
render(<Select options={options} value="2" onChange={() => {}} />);
const button = screen.getByRole('button');
fireEvent.click(button);
const selectedOption = screen.getAllByRole('option').find(
opt => opt.getAttribute('aria-selected') === 'true'
);
expect(selectedOption?.textContent).toContain('옵션 2');
});
});
describe('제어 컴포넌트 (options 모드)', () => {
it('value 변경에 따라 표시가 업데이트된다', () => {
const options = [
{ value: '1', label: '옵션 1' },
{ value: '2', label: '옵션 2' },
];
const TestComponent = () => {
const [value, setValue] = React.useState('1');
return (
<div>
<Select
options={options}
value={value}
onChange={(e) => setValue(String(e.target.value))}
/>
<button onClick={() => setValue('2')}>변경</button>
</div>
);
};
render(<TestComponent />);
// 초기값 확인
expect(screen.getByText('옵션 1')).toBeTruthy();
// 외부에서 값 변경
fireEvent.click(screen.getByText('변경'));
// 표시가 업데이트됨
expect(screen.getByText('옵션 2')).toBeTruthy();
});
});
describe('빈 options 처리', () => {
it('빈 배열일 때도 렌더링된다', () => {
render(<Select options={[]} value="" onChange={() => {}} />);
const button = screen.getByRole('button');
expect(button).toBeTruthy();
});
it('options가 배열이 아닐 때 기본 select로 폴백된다', () => {
// @ts-expect-error - 의도적으로 잘못된 타입 전달
const { container } = render(<Select options="invalid" />);
const select = container.querySelector('select');
expect(select).toBeTruthy();
});
});
});
@@ -0,0 +1,521 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { Table } from '../Table';
import { Thead } from '../Thead';
import { Tbody } from '../Tbody';
import { Tr } from '../Tr';
import { Th } from '../Th';
import { Td } from '../Td';
describe('Table 컴포넌트', () => {
describe('기본 렌더링', () => {
it('table 요소가 렌더링된다', () => {
const { container } = render(
<Table>
<tbody>
<tr>
<td>데이터</td>
</tr>
</tbody>
</Table>
);
const table = container.querySelector('table');
expect(table).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<Table>
<tbody>
<tr>
<td>테스트 데이터</td>
</tr>
</tbody>
</Table>
);
expect(screen.getByText('테스트 데이터')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<Table className="custom-table">
<tbody>
<tr>
<td>데이터</td>
</tr>
</tbody>
</Table>
);
const table = container.querySelector('table');
expect(table?.className).toContain('custom-table');
});
});
describe('Thead 컴포넌트', () => {
it('thead 요소가 렌더링된다', () => {
const { container } = render(
<table>
<Thead>
<tr>
<th>헤더</th>
</tr>
</Thead>
</table>
);
const thead = container.querySelector('thead');
expect(thead).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<Thead>
<tr>
<th>컬럼명</th>
</tr>
</Thead>
</table>
);
expect(screen.getByText('컬럼명')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<Thead className="custom-thead">
<tr>
<th>헤더</th>
</tr>
</Thead>
</table>
);
const thead = container.querySelector('thead');
expect(thead?.className).toContain('custom-thead');
});
});
describe('Tbody 컴포넌트', () => {
it('tbody 요소가 렌더링된다', () => {
const { container } = render(
<table>
<Tbody>
<tr>
<td>데이터</td>
</tr>
</Tbody>
</table>
);
const tbody = container.querySelector('tbody');
expect(tbody).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<Tbody>
<tr>
<td>테스트 데이터</td>
</tr>
</Tbody>
</table>
);
expect(screen.getByText('테스트 데이터')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<Tbody className="custom-tbody">
<tr>
<td>데이터</td>
</tr>
</Tbody>
</table>
);
const tbody = container.querySelector('tbody');
expect(tbody?.className).toContain('custom-tbody');
});
});
describe('Tr 컴포넌트', () => {
it('tr 요소가 렌더링된다', () => {
const { container } = render(
<table>
<tbody>
<Tr>
<td>셀</td>
</Tr>
</tbody>
</table>
);
const tr = container.querySelector('tr');
expect(tr).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<tbody>
<Tr>
<td>테스트 셀</td>
</Tr>
</tbody>
</table>
);
expect(screen.getByText('테스트 셀')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<tbody>
<Tr className="custom-tr">
<td>셀</td>
</Tr>
</tbody>
</table>
);
const tr = container.querySelector('tr');
expect(tr?.className).toContain('custom-tr');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(
<table>
<tbody>
<Tr onClick={handleClick}>
<td>클릭 가능한 행</td>
</Tr>
</tbody>
</table>
);
const tr = screen.getByText('클릭 가능한 행').closest('tr')!;
fireEvent.click(tr);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
describe('Th 컴포넌트', () => {
it('th 요소가 렌더링된다', () => {
const { container } = render(
<table>
<thead>
<tr>
<Th>헤더 셀</Th>
</tr>
</thead>
</table>
);
const th = container.querySelector('th');
expect(th).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<thead>
<tr>
<Th>이름</Th>
</tr>
</thead>
</table>
);
expect(screen.getByText('이름')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<thead>
<tr>
<Th className="custom-th">헤더</Th>
</tr>
</thead>
</table>
);
const th = container.querySelector('th');
expect(th?.className).toContain('custom-th');
});
it('scope 속성이 적용된다', () => {
const { container } = render(
<table>
<thead>
<tr>
<Th scope="col">컬럼</Th>
</tr>
</thead>
</table>
);
const th = container.querySelector('th');
expect(th?.scope).toBe('col');
});
it('onClick 이벤트가 작동한다 (정렬 가능한 헤더)', () => {
const handleClick = vi.fn();
render(
<table>
<thead>
<tr>
<Th onClick={handleClick}>정렬 가능한 컬럼</Th>
</tr>
</thead>
</table>
);
const th = screen.getByText('정렬 가능한 컬럼');
fireEvent.click(th);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
describe('Td 컴포넌트', () => {
it('td 요소가 렌더링된다', () => {
const { container } = render(
<table>
<tbody>
<tr>
<Td>데이터 셀</Td>
</tr>
</tbody>
</table>
);
const td = container.querySelector('td');
expect(td).toBeTruthy();
});
it('자식 요소를 렌더링한다', () => {
render(
<table>
<tbody>
<tr>
<Td>홍길동</Td>
</tr>
</tbody>
</table>
);
expect(screen.getByText('홍길동')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(
<table>
<tbody>
<tr>
<Td className="custom-td">데이터</Td>
</tr>
</tbody>
</table>
);
const td = container.querySelector('td');
expect(td?.className).toContain('custom-td');
});
it('colSpan 속성이 적용된다', () => {
const { container } = render(
<table>
<tbody>
<tr>
<Td colSpan={2}>병합된 셀</Td>
</tr>
</tbody>
</table>
);
const td = container.querySelector('td');
expect(td?.colSpan).toBe(2);
});
it('rowSpan 속성이 적용된다', () => {
const { container } = render(
<table>
<tbody>
<tr>
<Td rowSpan={2}>세로 병합</Td>
</tr>
<tr></tr>
</tbody>
</table>
);
const td = container.querySelector('td');
expect(td?.rowSpan).toBe(2);
});
});
describe('완전한 테이블 구조', () => {
it('thead와 tbody를 포함한 완전한 테이블이 렌더링된다', () => {
const { container } = render(
<Table>
<Thead>
<Tr>
<Th>이름</Th>
<Th>나이</Th>
<Th>이메일</Th>
</Tr>
</Thead>
<Tbody>
<Tr>
<Td>홍길동</Td>
<Td>30</Td>
<Td>hong@example.com</Td>
</Tr>
<Tr>
<Td>김철수</Td>
<Td>25</Td>
<Td>kim@example.com</Td>
</Tr>
</Tbody>
</Table>
);
const table = container.querySelector('table');
const thead = container.querySelector('thead');
const tbody = container.querySelector('tbody');
const ths = container.querySelectorAll('th');
const trs = tbody?.querySelectorAll('tr');
expect(table).toBeTruthy();
expect(thead).toBeTruthy();
expect(tbody).toBeTruthy();
expect(ths.length).toBe(3);
expect(trs?.length).toBe(2);
expect(screen.getByText('홍길동')).toBeTruthy();
expect(screen.getByText('김철수')).toBeTruthy();
});
it('여러 행과 열을 렌더링한다', () => {
render(
<Table>
<Tbody>
<Tr>
<Td>1</Td>
<Td>A</Td>
<Td>Alpha</Td>
</Tr>
<Tr>
<Td>2</Td>
<Td>B</Td>
<Td>Beta</Td>
</Tr>
<Tr>
<Td>3</Td>
<Td>C</Td>
<Td>Gamma</Td>
</Tr>
</Tbody>
</Table>
);
expect(screen.getByText('Alpha')).toBeTruthy();
expect(screen.getByText('Beta')).toBeTruthy();
expect(screen.getByText('Gamma')).toBeTruthy();
});
});
describe('HTML 속성', () => {
it('cellPadding이 적용된다', () => {
const { container } = render(
<Table cellPadding={10}>
<tbody>
<tr>
<td>데이터</td>
</tr>
</tbody>
</Table>
);
const table = container.querySelector('table');
expect(table?.cellPadding).toBe('10');
});
it('cellSpacing이 적용된다', () => {
const { container } = render(
<Table cellSpacing={5}>
<tbody>
<tr>
<td>데이터</td>
</tr>
</tbody>
</Table>
);
const table = container.querySelector('table');
expect(table?.cellSpacing).toBe('5');
});
});
describe('접근성', () => {
it('caption을 포함할 수 있다', () => {
render(
<Table>
<caption>사용자 목록</caption>
<Tbody>
<Tr>
<Td>데이터</Td>
</Tr>
</Tbody>
</Table>
);
expect(screen.getByText('사용자 목록')).toBeTruthy();
});
it('th의 scope 속성이 접근성을 향상시킨다', () => {
const { container } = render(
<Table>
<Thead>
<Tr>
<Th scope="col">이름</Th>
<Th scope="col">나이</Th>
</Tr>
</Thead>
<Tbody>
<Tr>
<Th scope="row">홍길동</Th>
<Td>30</Td>
</Tr>
</Tbody>
</Table>
);
const ths = container.querySelectorAll('th');
const colHeaders = Array.from(ths).filter((th) => th.scope === 'col');
const rowHeaders = Array.from(ths).filter((th) => th.scope === 'row');
expect(colHeaders.length).toBe(2);
expect(rowHeaders.length).toBe(1);
});
});
describe('복합 Props', () => {
it('여러 props와 스타일이 함께 적용된다', () => {
const { container } = render(
<Table className="border-collapse w-full" cellPadding={8}>
<Thead className="bg-gray-100">
<Tr>
<Th className="text-left" scope="col">
컬럼 1
</Th>
<Th className="text-right" scope="col">
컬럼 2
</Th>
</Tr>
</Thead>
<Tbody>
<Tr className="hover:bg-gray-50">
<Td className="py-2">데이터 1</Td>
<Td className="py-2 text-right">데이터 2</Td>
</Tr>
</Tbody>
</Table>
);
const table = container.querySelector('table');
const thead = container.querySelector('thead');
const tr = container.querySelector('tbody tr');
expect(table?.className).toContain('border-collapse');
expect(table?.className).toContain('w-full');
expect(thead?.className).toContain('bg-gray-100');
expect(tr?.className).toContain('hover:bg-gray-50');
});
});
});
@@ -0,0 +1,278 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import React from 'react';
import { Textarea } from '../Textarea';
describe('Textarea 컴포넌트', () => {
describe('기본 렌더링', () => {
it('textarea 요소가 렌더링된다', () => {
const { container } = render(<Textarea />);
const textarea = container.querySelector('textarea');
expect(textarea).toBeTruthy();
});
it('placeholder가 표시된다', () => {
render(<Textarea placeholder="내용을 입력하세요" />);
expect(screen.getByPlaceholderText('내용을 입력하세요')).toBeTruthy();
});
it('value가 설정된다', () => {
const { container } = render(<Textarea value="테스트 내용" onChange={() => {}} />);
const textarea = container.querySelector('textarea') as HTMLTextAreaElement;
expect(textarea.value).toBe('테스트 내용');
});
it('defaultValue가 설정된다', () => {
const { container } = render(<Textarea defaultValue="기본 내용" />);
const textarea = container.querySelector('textarea') as HTMLTextAreaElement;
expect(textarea.value).toBe('기본 내용');
});
});
describe('이벤트 핸들링', () => {
it('onChange 핸들러가 호출된다', () => {
const handleChange = vi.fn();
const { container } = render(<Textarea onChange={handleChange} />);
const textarea = container.querySelector('textarea')!;
fireEvent.change(textarea, { target: { value: '새 내용' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
it('onFocus 핸들러가 호출된다', () => {
const handleFocus = vi.fn();
const { container } = render(<Textarea onFocus={handleFocus} />);
const textarea = container.querySelector('textarea')!;
fireEvent.focus(textarea);
expect(handleFocus).toHaveBeenCalledTimes(1);
});
it('onBlur 핸들러가 호출된다', () => {
const handleBlur = vi.fn();
const { container } = render(<Textarea onBlur={handleBlur} />);
const textarea = container.querySelector('textarea')!;
fireEvent.blur(textarea);
expect(handleBlur).toHaveBeenCalledTimes(1);
});
it('onKeyDown 핸들러가 호출된다', () => {
const handleKeyDown = vi.fn();
const { container } = render(<Textarea onKeyDown={handleKeyDown} />);
const textarea = container.querySelector('textarea')!;
fireEvent.keyDown(textarea, { key: 'Enter' });
expect(handleKeyDown).toHaveBeenCalledTimes(1);
});
it('onKeyUp 핸들러가 호출된다', () => {
const handleKeyUp = vi.fn();
const { container } = render(<Textarea onKeyUp={handleKeyUp} />);
const textarea = container.querySelector('textarea')!;
fireEvent.keyUp(textarea, { key: 'a' });
expect(handleKeyUp).toHaveBeenCalledTimes(1);
});
});
describe('제어 컴포넌트', () => {
it('제어 컴포넌트로 작동한다', () => {
const TestComponent = () => {
const [value, setValue] = React.useState('초기값');
return <Textarea value={value} onChange={(e) => setValue(e.target.value)} />;
};
const { container } = render(<TestComponent />);
const textarea = container.querySelector('textarea')!;
expect((textarea as HTMLTextAreaElement).value).toBe('초기값');
fireEvent.change(textarea, { target: { value: '변경된 값' } });
expect((textarea as HTMLTextAreaElement).value).toBe('변경된 값');
});
});
describe('HTML 속성', () => {
it('disabled 속성이 적용된다', () => {
const { container } = render(<Textarea disabled />);
const textarea = container.querySelector('textarea');
expect(textarea?.disabled).toBe(true);
});
it('readOnly 속성이 적용된다', () => {
const { container } = render(<Textarea readOnly />);
const textarea = container.querySelector('textarea');
expect(textarea?.readOnly).toBe(true);
});
it('required 속성이 적용된다', () => {
const { container } = render(<Textarea required />);
const textarea = container.querySelector('textarea');
expect(textarea?.required).toBe(true);
});
it('name 속성이 적용된다', () => {
const { container } = render(<Textarea name="description" />);
const textarea = container.querySelector('textarea');
expect(textarea?.name).toBe('description');
});
it('id 속성이 적용된다', () => {
const { container } = render(<Textarea id="comment-textarea" />);
const textarea = container.querySelector('textarea');
expect(textarea?.id).toBe('comment-textarea');
});
it('rows 속성이 적용된다', () => {
const { container } = render(<Textarea rows={5} />);
const textarea = container.querySelector('textarea');
expect(textarea?.rows).toBe(5);
});
it('cols 속성이 적용된다', () => {
const { container } = render(<Textarea cols={50} />);
const textarea = container.querySelector('textarea');
expect(textarea?.cols).toBe(50);
});
it('maxLength 속성이 적용된다', () => {
const { container } = render(<Textarea maxLength={100} />);
const textarea = container.querySelector('textarea');
expect(textarea?.maxLength).toBe(100);
});
it('minLength 속성이 적용된다', () => {
const { container } = render(<Textarea minLength={10} />);
const textarea = container.querySelector('textarea');
expect(textarea?.minLength).toBe(10);
});
it('wrap 속성이 적용된다', () => {
const { container } = render(<Textarea wrap="hard" />);
const textarea = container.querySelector('textarea');
expect(textarea?.wrap).toBe('hard');
});
});
describe('Label 및 Error Props', () => {
it('label prop이 존재한다', () => {
// label prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Textarea label="설명" />);
const textarea = container.querySelector('textarea');
expect(textarea).toBeTruthy();
});
it('error prop이 존재한다', () => {
// error prop은 있지만 렌더링하지 않음 (부모에서 처리)
const { container } = render(<Textarea error="필수 입력 항목입니다" />);
const textarea = container.querySelector('textarea');
expect(textarea).toBeTruthy();
});
});
describe('사용자 정의 Props', () => {
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Textarea className="custom-textarea" />);
const textarea = container.querySelector('textarea');
expect(textarea?.className).toContain('custom-textarea');
});
it('aria-label이 적용된다', () => {
const { container } = render(<Textarea aria-label="댓글 입력" />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('aria-label')).toBe('댓글 입력');
});
it('aria-describedby가 적용된다', () => {
const { container } = render(<Textarea aria-describedby="description-help" />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('aria-describedby')).toBe('description-help');
});
it('data 속성이 적용된다', () => {
const { container } = render(<Textarea data-testid="test-textarea" />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('data-testid')).toBe('test-textarea');
});
it('autoComplete 속성이 적용된다', () => {
const { container } = render(<Textarea autoComplete="off" />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('autocomplete')).toBe('off');
});
// autoFocus는 jsdom 환경에서 제대로 테스트되지 않으므로 생략
it('spellCheck 속성이 적용된다', () => {
const { container } = render(<Textarea spellCheck={false} />);
const textarea = container.querySelector('textarea');
expect(textarea?.getAttribute('spellcheck')).toBe('false');
});
});
describe('Resize 동작', () => {
it('기본 resize 동작이 유지된다', () => {
const { container } = render(<Textarea />);
const textarea = container.querySelector('textarea');
// CSS resize 속성은 기본적으로 'both' 또는 브라우저 기본값
expect(textarea).toBeTruthy();
});
it('resize 스타일을 커스텀할 수 있다', () => {
const { container } = render(<Textarea style={{ resize: 'vertical' }} />);
const textarea = container.querySelector('textarea') as HTMLTextAreaElement;
expect(textarea.style.resize).toBe('vertical');
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleChange = vi.fn();
const { container } = render(
<Textarea
name="description"
value="테스트 내용"
onChange={handleChange}
rows={5}
cols={40}
maxLength={500}
required
className="custom-textarea"
aria-label="상품 설명"
placeholder="상품 설명을 입력하세요"
/>
);
const textarea = container.querySelector('textarea')!;
expect(textarea.name).toBe('description');
expect((textarea as HTMLTextAreaElement).value).toBe('테스트 내용');
expect(textarea.rows).toBe(5);
expect(textarea.cols).toBe(40);
expect(textarea.maxLength).toBe(500);
expect(textarea.required).toBe(true);
expect(textarea.className).toContain('custom-textarea');
expect(textarea.getAttribute('aria-label')).toBe('상품 설명');
expect(textarea.placeholder).toBe('상품 설명을 입력하세요');
fireEvent.change(textarea, { target: { value: '새 내용' } });
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
describe('줄바꿈 처리', () => {
it('여러 줄 텍스트를 처리한다', () => {
const multilineText = '첫 번째 줄\n두 번째 줄\n세 번째 줄';
const { container } = render(<Textarea value={multilineText} onChange={() => {}} />);
const textarea = container.querySelector('textarea') as HTMLTextAreaElement;
expect(textarea.value).toBe(multilineText);
});
});
});
@@ -0,0 +1,295 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { H1 } from '../H1';
import { H2 } from '../H2';
import { H3 } from '../H3';
import { P } from '../P';
import { Span } from '../Span';
import { Label } from '../Label';
describe('Typography 컴포넌트', () => {
describe('H1 컴포넌트', () => {
it('h1 요소가 렌더링된다', () => {
const { container } = render(<H1>제목 1</H1>);
const h1 = container.querySelector('h1');
expect(h1).toBeTruthy();
expect(h1?.textContent).toBe('제목 1');
});
it('자식 요소를 렌더링한다', () => {
render(<H1>Main Heading</H1>);
expect(screen.getByText('Main Heading')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<H1 className="custom-h1">제목</H1>);
const h1 = container.querySelector('h1');
expect(h1?.className).toContain('custom-h1');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<H1 onClick={handleClick}>클릭 가능한 제목</H1>);
const h1 = screen.getByText('클릭 가능한 제목');
fireEvent.click(h1);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('id 속성이 적용된다', () => {
const { container } = render(<H1 id="main-title">제목</H1>);
const h1 = container.querySelector('h1');
expect(h1?.id).toBe('main-title');
});
});
describe('H2 컴포넌트', () => {
it('h2 요소가 렌더링된다', () => {
const { container } = render(<H2>제목 2</H2>);
const h2 = container.querySelector('h2');
expect(h2).toBeTruthy();
expect(h2?.textContent).toBe('제목 2');
});
it('자식 요소를 렌더링한다', () => {
render(<H2>Sub Heading</H2>);
expect(screen.getByText('Sub Heading')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<H2 className="custom-h2">제목</H2>);
const h2 = container.querySelector('h2');
expect(h2?.className).toContain('custom-h2');
});
});
describe('H3 컴포넌트', () => {
it('h3 요소가 렌더링된다', () => {
const { container } = render(<H3>제목 3</H3>);
const h3 = container.querySelector('h3');
expect(h3).toBeTruthy();
expect(h3?.textContent).toBe('제목 3');
});
it('자식 요소를 렌더링한다', () => {
render(<H3>Section Heading</H3>);
expect(screen.getByText('Section Heading')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<H3 className="custom-h3">제목</H3>);
const h3 = container.querySelector('h3');
expect(h3?.className).toContain('custom-h3');
});
});
describe('P 컴포넌트', () => {
it('p 요소가 렌더링된다', () => {
const { container } = render(<P>단락 텍스트</P>);
const p = container.querySelector('p');
expect(p).toBeTruthy();
expect(p?.textContent).toBe('단락 텍스트');
});
it('자식 요소를 렌더링한다', () => {
render(<P>This is a paragraph.</P>);
expect(screen.getByText('This is a paragraph.')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<P className="custom-paragraph">텍스트</P>);
const p = container.querySelector('p');
expect(p?.className).toContain('custom-paragraph');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<P onClick={handleClick}>클릭 가능한 단락</P>);
const p = screen.getByText('클릭 가능한 단락');
fireEvent.click(p);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('여러 줄 텍스트를 렌더링한다', () => {
const multilineText = '첫 번째 줄\n두 번째 줄';
render(<P>{multilineText}</P>);
expect(screen.getByText(/첫 번째 줄/)).toBeTruthy();
});
});
describe('Span 컴포넌트', () => {
it('span 요소가 렌더링된다', () => {
const { container } = render(<Span>인라인 텍스트</Span>);
const span = container.querySelector('span');
expect(span).toBeTruthy();
expect(span?.textContent).toBe('인라인 텍스트');
});
it('자식 요소를 렌더링한다', () => {
render(<Span>Inline text</Span>);
expect(screen.getByText('Inline text')).toBeTruthy();
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Span className="custom-span">텍스트</Span>);
const span = container.querySelector('span');
expect(span?.className).toContain('custom-span');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<Span onClick={handleClick}>클릭 가능한 span</Span>);
const span = screen.getByText('클릭 가능한 span');
fireEvent.click(span);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('data 속성이 적용된다', () => {
const { container } = render(<Span data-testid="test-span">텍스트</Span>);
const span = container.querySelector('span');
expect(span?.getAttribute('data-testid')).toBe('test-span');
});
});
describe('Label 컴포넌트', () => {
it('label 요소가 렌더링된다', () => {
const { container } = render(<Label>레이블 텍스트</Label>);
const label = container.querySelector('label');
expect(label).toBeTruthy();
expect(label?.textContent).toBe('레이블 텍스트');
});
it('자식 요소를 렌더링한다', () => {
render(<Label>Form Label</Label>);
expect(screen.getByText('Form Label')).toBeTruthy();
});
it('htmlFor 속성이 적용된다', () => {
const { container } = render(<Label htmlFor="input-id">레이블</Label>);
const label = container.querySelector('label');
expect(label?.htmlFor).toBe('input-id');
});
it('사용자 정의 클래스가 추가된다', () => {
const { container } = render(<Label className="custom-label">레이블</Label>);
const label = container.querySelector('label');
expect(label?.className).toContain('custom-label');
});
it('onClick 이벤트가 작동한다', () => {
const handleClick = vi.fn();
render(<Label onClick={handleClick}>클릭 가능한 레이블</Label>);
const label = screen.getByText('클릭 가능한 레이블');
fireEvent.click(label);
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('input과 연결된다', () => {
const { container } = render(
<>
<Label htmlFor="test-input">이름</Label>
<input id="test-input" type="text" />
</>
);
const label = container.querySelector('label');
const input = container.querySelector('input');
expect(label?.htmlFor).toBe('test-input');
expect(input?.id).toBe('test-input');
});
});
describe('공통 HTML 속성', () => {
it('모든 컴포넌트에 style 속성이 적용된다', () => {
const style = { color: 'red', fontSize: '20px' };
const { container: h1Container } = render(<H1 style={style}>H1</H1>);
const { container: pContainer } = render(<P style={style}>P</P>);
const { container: spanContainer } = render(<Span style={style}>Span</Span>);
const h1 = h1Container.querySelector('h1') as HTMLElement;
const p = pContainer.querySelector('p') as HTMLElement;
const span = spanContainer.querySelector('span') as HTMLElement;
expect(h1.style.color).toBe('red');
expect(p.style.color).toBe('red');
expect(span.style.color).toBe('red');
});
it('모든 컴포넌트에 aria 속성이 적용된다', () => {
const { container: h1Container } = render(<H1 aria-label="메인 제목">H1</H1>);
const { container: pContainer } = render(<P aria-describedby="desc">P</P>);
const { container: spanContainer } = render(<Span role="status">Span</Span>);
const h1 = h1Container.querySelector('h1');
const p = pContainer.querySelector('p');
const span = spanContainer.querySelector('span');
expect(h1?.getAttribute('aria-label')).toBe('메인 제목');
expect(p?.getAttribute('aria-describedby')).toBe('desc');
expect(span?.getAttribute('role')).toBe('status');
});
});
describe('중첩된 요소', () => {
it('P 안에 Span이 중첩된다', () => {
render(
<P>
일반 텍스트 <Span className="highlight">강조 텍스트</Span> 계속
</P>
);
expect(screen.getByText(/일반 텍스트/)).toBeTruthy();
expect(screen.getByText('강조 텍스트')).toBeTruthy();
});
it('Label 안에 Span이 중첩된다', () => {
render(
<Label>
<Span>필수</Span> 사용자명
</Label>
);
expect(screen.getByText('필수')).toBeTruthy();
expect(screen.getByText(/사용자명/)).toBeTruthy();
});
it('H1 안에 Span이 중첩된다', () => {
render(
<H1>
메인 제목 <Span className="subtitle">부제목</Span>
</H1>
);
expect(screen.getByText(/메인 제목/)).toBeTruthy();
expect(screen.getByText('부제목')).toBeTruthy();
});
});
describe('복합 Props', () => {
it('여러 props가 함께 적용된다', () => {
const handleClick = vi.fn();
const { container } = render(
<P
id="intro"
className="text-lg text-gray-700"
style={{ marginBottom: '20px' }}
onClick={handleClick}
data-testid="intro-paragraph"
>
소개 텍스트
</P>
);
const p = container.querySelector('p')!;
expect(p.id).toBe('intro');
expect(p.className).toContain('text-lg');
expect(p.className).toContain('text-gray-700');
expect((p as HTMLElement).style.marginBottom).toBe('20px');
expect(p.getAttribute('data-testid')).toBe('intro-paragraph');
fireEvent.click(p);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
});
@@ -0,0 +1,46 @@
/**
* 기본 HTML 매핑 컴포넌트 Export
*
* DOM 요소에 직접 매핑되는 기본 컴포넌트들
*/
export { Button, type ButtonProps } from './Button';
export { FileInput, type FileInputProps } from './FileInput';
export { Input, type InputProps } from './Input';
export { Textarea, type TextareaProps } from './Textarea';
export { Label, type LabelProps } from './Label';
export { Div, type DivProps } from './Div';
export { Span, type SpanProps } from './Span';
export { P, type PProps } from './P';
export { Img, type ImgProps } from './Img';
export { H1, type H1Props } from './H1';
export { H2, type H2Props } from './H2';
export { H3, type H3Props } from './H3';
export { H4, type H4Props } from './H4';
export { Ul, type UlProps } from './Ul';
export { Ol, type OlProps } from './Ol';
export { Li, type LiProps } from './Li';
export { A, type AProps } from './A';
export { Form, type FormProps } from './Form';
export { Select, type SelectProps } from './Select';
export { Option, type OptionProps } from './Option';
export { Optgroup, type OptgroupProps } from './Optgroup';
export { Checkbox, type CheckboxProps } from './Checkbox';
export { Table, type TableProps } from './Table';
export { Thead, type TheadProps } from './Thead';
export { Tbody, type TbodyProps } from './Tbody';
export { Tfoot, type TfootProps } from './Tfoot';
export { Tr, type TrProps } from './Tr';
export { Th, type ThProps } from './Th';
export { Td, type TdProps } from './Td';
export { Nav, type NavProps } from './Nav';
export { Section, type SectionProps } from './Section';
export { Svg, type SvgProps } from './Svg';
export { Icon, type IconProps } from './Icon';
export { Code, type CodeProps } from './Code';
export { Pre, type PreProps } from './Pre';
export { Fragment, type FragmentProps } from './Fragment';
export { Hr, type HrProps } from './Hr';
// Icon 타입 정의 (enum 및 타입)
export { IconName, type IconStyle, type IconSize } from './IconTypes';