Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix useDebounceCallback isPending logic #610

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Prev Previous commit
Next Next commit
Add tests for useDebounceCallback
that test the `isPending` behavior
  • Loading branch information
simon-lammes authored Aug 7, 2024
commit 29002a5abe21270d329ad14b0bc837f183dcddf4
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,45 @@ describe('useDebounceCallback()', () => {
// The callback should be invoked immediately after flushing
expect(debouncedCallback).toHaveBeenCalled()
})

it('should update isPending on invocations', () => {
const delay = 100
const callback = vitest.fn()
const { result } = renderHook(() => useDebounceCallback(callback, delay))

act(() => {
result.current('test1')
result.current('test2')
})

expect(result.current.isPending()).toBeTruthy()

// Fast-forward time
vitest.advanceTimersByTime(200)

expect(result.current.isPending()).toBeFalsy()
})

it('should update isPending on invocations even if callback errors out', () => {
const delay = 100
const errorMessage =
'Mock implementation throws error for testing purposes.'
const callback = vitest.fn().mockImplementation(() => {
throw new Error(errorMessage)
})
const { result } = renderHook(() => useDebounceCallback(callback, delay))

act(() => {
result.current('test1')
result.current('test2')
})

expect(result.current.isPending()).toBeTruthy()

// Forwarding time will invoke the debounced mock function which throws an error.
expect(() => vitest.advanceTimersByTime(200)).toThrowError(errorMessage)

// Even though the mock implementation threw an error, isPending should still be updated to false.
expect(result.current.isPending()).toBeFalsy()
})
})