diff --git a/src/components/Search/index.jsx b/src/components/Search/index.jsx index 79de9e111..2436e9b3e 100644 --- a/src/components/Search/index.jsx +++ b/src/components/Search/index.jsx @@ -59,10 +59,10 @@ const Search = React.forwardRef( } }; - const onInputSearch = (searchValue) => { - const search = debounceInterval ? _.debounce(onSearch, debounceInterval) : onSearch; - search(searchValue); - }; + const onInputSearch = React.useMemo( + () => _.debounce((searchValue) => onSearch(searchValue), debounceInterval), + [debounceInterval, onSearch] + ); const onSearchButtonClick = (event) => { event.preventDefault(); diff --git a/src/components/Search/index.spec.jsx b/src/components/Search/index.spec.jsx index 82413f541..89a8754fa 100644 --- a/src/components/Search/index.spec.jsx +++ b/src/components/Search/index.spec.jsx @@ -190,19 +190,36 @@ describe('Value Changed', () => { expect(callbacks.onSearch).toHaveBeenCalledWith('v'); }); - it('should fire onSearch after debounceInterval', async () => { + it('should fire onSearch immediately when debounceInterval is not set', async () => { const callbacks = { onSearch: jest.fn(), }; - render(); + render(); await user.type(screen.getByTestId('search-input'), 'new-value'); - expect(callbacks.onSearch).not.toHaveBeenCalledWith('new-value'); - await sleep(500); expect(callbacks.onSearch).toHaveBeenCalledWith('new-value'); }); + it('should debounce onSearch calls when debounceInterval is set', async () => { + const callbacks = { + onSearch: jest.fn(), + }; + render(); + + await user.type(screen.getByTestId('search-input'), 'n'); + await user.type(screen.getByTestId('search-input'), 'e'); + await user.type(screen.getByTestId('search-input'), 'w'); + expect(callbacks.onSearch).not.toHaveBeenCalledWith('n'); + expect(callbacks.onSearch).not.toHaveBeenCalledWith('ne'); + expect(callbacks.onSearch).not.toHaveBeenCalledWith('new'); + + await sleep(200); + expect(callbacks.onSearch).not.toHaveBeenCalledWith('n'); + expect(callbacks.onSearch).not.toHaveBeenCalledWith('ne'); + expect(callbacks.onSearch).toHaveBeenCalledWith('new'); + }); + it('should not fire onSearch when value changed if searchOnEnter is true', async () => { const callbacks = { onSearch: jest.fn(),