Skip to content

Commit

Permalink
refactor: use debounce 테스트 코드 작성 및 리팩토링 (#ATR-600)
Browse files Browse the repository at this point in the history
  • Loading branch information
LC-02s committed Aug 2, 2024
1 parent 8ab6320 commit d36c63f
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { act, renderHook } from '@testing-library/react'
import useDebounce from './useDebounce'

describe('@/use-debounce', () => {
const delay = 500
const initialValue = 'initial value'
const changedValue = 'changed value'

beforeEach(() => {
vi.useFakeTimers()
})

afterEach(() => {
vi.useRealTimers()
})

test('지연된 후에 값이 올바르게 변경됨', () => {
const { result, rerender } = renderHook(
({ value }) => useDebounce(value, delay),
{ initialProps: { value: initialValue } },
)

expect(result.current).toBe(initialValue)

rerender({ value: changedValue })

expect(result.current).toBe(initialValue)

act(() => vi.advanceTimersByTime(delay * 2))

expect(result.current).toBe(changedValue)
})

test('unmount 됐을 때 실행 중이던 debounce가 취소됨', () => {
const { result, rerender, unmount } = renderHook(
({ value }) => useDebounce(value, delay),
{ initialProps: { value: initialValue } },
)

expect(result.current).toBe(initialValue)

rerender({ value: changedValue })

expect(result.current).toBe(initialValue)

act(() => vi.advanceTimersByTime(delay / 2))

unmount()

act(() => vi.advanceTimersByTime(delay))

expect(result.current).toBe(initialValue)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ export default function useDebounce<T>(value: T, delay: number) {
const [debouncedValue, setDebouncedValue] = React.useState<T>(value)

React.useEffect(() => {
const timeoutId = setTimeout(() => {
setDebouncedValue(value)
}, delay)
const timeoutId = setTimeout(() => setDebouncedValue(value), delay)

return () => clearTimeout(timeoutId)
return () => {
clearTimeout(timeoutId)
}
}, [value, delay])

return debouncedValue
Expand Down

0 comments on commit d36c63f

Please sign in to comment.