Testing useDebouncedValue hooks

Rex Ye
1 min readJan 7, 2022

--

Testing (Series)
Understanding Unit Test From The Best Book On The Topic
Testing Ag-Grid React’s Custom Cell Renderer Component
Testing ErrorFallback Component
Testing useDebouncedValue Hook
Testing a HTTP Client Adaptor Hook useClient
Testing a HTTP Error Handler Utility Hook
Testing a Generic Fetch Item List hook with Mock Service
Introducing @mockapi/msw, mock an API server for your entities without writing any code with Mock Service Worker
Testing a Generic Save Item Hook with MSW and @mockapi/msw
Testing a Text Field component integrating Mui’s Text Field with React Hook Form

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

One weird and interesting behavior of Jest’s fake timer is that the fake timer somehow got influenced by other tests before it:

If I move the second describe block (not using the fake timer) before the first, the last assessment fails:

...
act(() => {
jest.advanceTimersByTime(1);
});
expect(debouncedValue.textContent).toBe(‘3’); // fails, got 0 instead of 3
expect(value.textContent).toBe(‘3’);
...

If anyone knows why the above fails, please, please let me know, I would be most grateful.

Originally published at https://dev.to on January 7, 2022.

--

--

Rex Ye
Rex Ye

Written by Rex Ye

.net, Angular, React. Creator of epicerp.app

No responses yet