Skip to content

Instantly share code, notes, and snippets.

@claudiainbytes
Created February 11, 2026 19:06
Show Gist options
  • Select an option

  • Save claudiainbytes/8cb80295669bfaa782efee746deb1908 to your computer and use it in GitHub Desktop.

Select an option

Save claudiainbytes/8cb80295669bfaa782efee746deb1908 to your computer and use it in GitHub Desktop.
Testing con Timers y Debounce
// 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