Created
February 11, 2026 19:06
-
-
Save claudiainbytes/8cb80295669bfaa782efee746deb1908 to your computer and use it in GitHub Desktop.
Testing con Timers y Debounce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Component con debounce | |
| const SearchInput = ({ onSearch }) => { | |
| const [value, setValue] = useState('') | |
| useEffect(() => { | |
| const timer = setTimeout(() => { | |
| onSearch(value) | |
| }, 300) | |
| return () => clearTimeout(timer) | |
| }, [value, onSearch]) | |
| return ( | |
| <input | |
| value={value} | |
| onChange={(e) => setValue(e.target.value)} | |
| placeholder="Search..." | |
| /> | |
| ) | |
| } | |
| // Test | |
| import { vi } from 'vitest' | |
| describe('SearchInput with debounce', () => { | |
| beforeEach(() => { | |
| vi.useFakeTimers() | |
| }) | |
| afterEach(() => { | |
| vi.restoreAllMocks() | |
| }) | |
| it('hace debounce de la búsqueda', async () => { | |
| const user = userEvent.setup({ delay: null }) // Importante para fake timers | |
| const handleSearch = vi.fn() | |
| render(<SearchInput onSearch={handleSearch} />) | |
| const input = screen.getByPlaceholderText(/search/i) | |
| await user.type(input, 'test') | |
| // No debería llamar inmediatamente | |
| expect(handleSearch).not.toHaveBeenCalled() | |
| // Avanzar tiempo | |
| act(() => { | |
| vi.advanceTimersByTime(300) | |
| }) | |
| // Ahora sí debería llamar | |
| expect(handleSearch).toHaveBeenCalledWith('test') | |
| expect(handleSearch).toHaveBeenCalledTimes(1) | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment