Skip to content

Commit

Permalink
feat(#133): useTagInput 테스트 코드
Browse files Browse the repository at this point in the history
  • Loading branch information
naarang committed Nov 24, 2024
1 parent cc0f8b4 commit 09e2655
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions apps/frontend/src/shared/tagInput/useTagInput.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { fireEvent, render, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vitest } from 'vitest';
import { useTagInput } from './useTagInput';

const mockOnChange = vitest.fn();

function TagInputComponent({ value, onChange }: { value: string[]; onChange: (tags: string[]) => void }) {
const { inputRef, onInputKeyDown } = useTagInput(value, onChange);

return <input ref={inputRef} onKeyDown={onInputKeyDown} aria-label="tag-input" />;
}

describe('useTagInput', () => {
beforeEach(() => {
vitest.spyOn(console, 'error').mockImplementation(() => {});
});

afterEach(() => {
vitest.restoreAllMocks();
});

test('Enter 키 입력으로 태그가 추가되어야 한다.', () => {
const { getByLabelText } = render(<TagInputComponent value={[]} onChange={mockOnChange} />);

const input = getByLabelText('tag-input');
fireEvent.change(input, { target: { value: 'new tag' } });
fireEvent.keyDown(input, { key: 'Enter' });

expect(mockOnChange).toHaveBeenCalledWith(['new tag']);
expect(input).toHaveValue('');
});

test('공백 문자열은 태그로 추가되지 않아야 한다.', () => {
const { getByLabelText } = render(<TagInputComponent value={[]} onChange={mockOnChange} />);

const input = getByLabelText('tag-input');
fireEvent.change(input, { target: { value: ' ' } });
fireEvent.keyDown(input, { key: 'Enter' });

expect(mockOnChange).not.toHaveBeenCalled();
});

test('removeTag 함수는 해당 태그를 삭제시켜야한다.', () => {
const initialTags = ['tag1', 'tag2', 'tag3'];

const { result } = renderHook(() => useTagInput(initialTags, mockOnChange));

result.current.removeTag(0);

expect(mockOnChange).toHaveBeenCalledWith(['tag2', 'tag3']);
});
});

0 comments on commit 09e2655

Please sign in to comment.