Skip to content

Commit

Permalink
fix: debug interval not working in Search component
Browse files Browse the repository at this point in the history
  • Loading branch information
romi-h committed Jan 29, 2024
1 parent 3cef107 commit aefacab
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
8 changes: 4 additions & 4 deletions src/components/Search/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
25 changes: 21 additions & 4 deletions src/components/Search/index.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<Search {...callbacks} debounceInterval={500} />);
render(<Search {...callbacks} />);

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(<Search {...callbacks} debounceInterval={200} />);

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(),
Expand Down

0 comments on commit aefacab

Please sign in to comment.