Cách Dùng AI Generate Unit Test Cho React Components
Hướng dẫn sử dụng AI tools để generate unit tests chất lượng cho React components. Tiết kiệm thời gian viết test mà vẫn đảm bảo coverage.
Viết test là việc quan trọng nhưng tốn thời gian. AI có thể giúp generate 70-80% test cases, bạn chỉ cần review và bổ sung edge cases. Đây là workflow mình dùng.
Tại sao dùng AI viết test?
Không phải lười — mà là hiệu quả. AI generate test nhanh, cover nhiều cases bạn có thể quên. Bạn focus vào logic phức tạp, AI handle phần boilerplate.
Setup: Vitest + React Testing Library
Stack testing mình recommend cho React/Next.js:
npm install -D vitest @testing-library/react @testing-library/jest-dom
npm install -D @testing-library/user-event jsdom @vitejs/plugin-react
Workflow thực tế
Bước 1: Viết component trước
// components/SearchInput.tsx
import { useState, useEffect, useCallback } from 'react';
import { useDebounce } from '@/hooks/useDebounce';
import { Search, X } from 'lucide-react';
interface SearchInputProps {
onSearch: (query: string) => void;
placeholder?: string;
debounceMs?: number;
}
export function SearchInput({
onSearch,
placeholder = 'Tìm kiếm...',
debounceMs = 300,
}: SearchInputProps) {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, debounceMs);
useEffect(() => {
onSearch(debouncedQuery);
}, [debouncedQuery, onSearch]);
const handleClear = useCallback(() => {
setQuery('');
}, []);
return (
<div className="relative">
<Search className="absolute left-3 top-1/2" size={18} />
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={placeholder}
className="w-full pl-10 pr-10 py-2 border rounded-lg"
aria-label="Search"
/>
{query && (
<button onClick={handleClear} aria-label="Clear search">
<X size={18} />
</button>
)}
</div>
);
}
Bước 2: Prompt AI generate tests
Dùng Claude Code hoặc Cursor, prompt:
Viết unit tests cho SearchInput component bằng Vitest + RTL.
Cover: render default, custom placeholder, typing triggers onSearch
với debounce, clear button xuất hiện khi có text, clear button
reset input, aria labels cho accessibility.
Bước 3: Review và bổ sung
AI sẽ generate khoảng 6-8 test cases. Bạn cần review:
- Test có đúng behavior không? (không test implementation details)
- Mock có hợp lý không? (đặc biệt với hooks)
- Edge cases: empty string, special characters, rapid typing
- Async behavior: debounce timing có đúng không?
Patterns AI test hay bỏ qua
Error boundaries: AI hiếm khi test component throw error. Concurrent updates: Rapid state changes, race conditions. SSR compatibility: Component có work khi server render không? Memory leaks: Cleanup effects khi unmount.
Kết luận
AI generate test = 70% done. 30% còn lại — edge cases, integration tests, và đảm bảo tests thực sự test đúng thứ — vẫn cần human judgment. Nhưng tiết kiệm 70% thời gian viết boilerplate là win lớn.
Admin
Bình luận (0)
Đăng nhập để bình luận
Chưa có bình luận nào. Hãy là người đầu tiên!