Testing useDebouncedValue hooks

Subject Under Test(sut)

A hook that debounces value to eliminate the performance penalty caused by rapid changes to a value. Source: usehooks.com

Behaviour:

Should only emit the last value change when specified debounce time is past.

Code:

Notes:

  1. The test uses a React Component to test the sut’s behaviour. It shows how the hook should be used.
  2. The Test uses useFakeTimers to control the pass of time and assert when the debounced value should and should not be changed
...
act(() => {
jest.advanceTimersByTime(1);
});
expect(debouncedValue.textContent).toBe(‘3’); // fails, got 0 instead of 3
expect(value.textContent).toBe(‘3’);
...

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store