From 5a6c51dbc6958673dc1cba33b15a993ddb441087 Mon Sep 17 00:00:00 2001 From: Lee-Dongwook Date: Mon, 28 Oct 2024 09:56:30 +0900 Subject: [PATCH] =?UTF-8?q?feat=20:=20UseDebounce=20=ED=9B=85=20=ED=85=8C?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8=20=EC=8A=A4=ED=81=AC=EB=A6=BD=ED=8A=B8=20?= =?UTF-8?q?=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/test/useDebounce.test.ts | 79 ++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 src/hooks/test/useDebounce.test.ts diff --git a/src/hooks/test/useDebounce.test.ts b/src/hooks/test/useDebounce.test.ts new file mode 100644 index 0000000..b4cf878 --- /dev/null +++ b/src/hooks/test/useDebounce.test.ts @@ -0,0 +1,79 @@ +import { renderHook, act } from '@testing-library/react'; +import { useDebounce } from '@/hooks/useDebounce'; + +jest.useFakeTimers(); + +describe('useDebounce 테스트', () => { + it('지연 시간 후에 값이 업데이트 되어야 한다.', () => { + const initialDelay = 500; + const { result, rerender } = renderHook( + ({ value, delay }) => useDebounce(value, delay), + { + initialProps: { value: 'initial', delay: initialDelay }, + } + ); + expect(result.current).toBe('initial'); + + rerender({ value: 'updated', delay: initialDelay }); + + act(() => { + jest.advanceTimersByTime(initialDelay); + }); + + expect(result.current).toBe('updated'); + }); + + it('지연 시간 내에 여러 값이 변경되어도 마지막 값만 반영되어야 한다.', () => { + const initialDelay = 500; + const { result, rerender } = renderHook( + ({ value, delay }) => useDebounce(value, delay), + { + initialProps: { value: 'initial', delay: initialDelay }, + } + ); + + rerender({ value: 'first change', delay: initialDelay }); + act(() => { + jest.advanceTimersByTime(100); + }); + + rerender({ value: 'second change', delay: initialDelay }); + act(() => { + jest.advanceTimersByTime(200); + }); + + expect(result.current).toBe('initial'); + + act(() => { + jest.advanceTimersByTime(200); + }); + + expect(result.current).toBe('second change'); + }); + + it('지연 시간이 변경되면 타이머가 초기화되어야 한다.', () => { + const initialDelay = 300; + const updatedDelay = 500; + const { result, rerender } = renderHook( + ({ value, delay }) => useDebounce(value, delay), + { + initialProps: { value: 'initial', delay: initialDelay }, + } + ); + + rerender({ value: 'first change', delay: initialDelay }); + act(() => { + jest.advanceTimersByTime(150); + }); + + rerender({ value: 'first change', delay: updatedDelay }); + + expect(result.current).toBe('initial'); + + act(() => { + jest.advanceTimersByTime(500); + }); + + expect(result.current).toBe('first change'); + }); +});