-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathdebouncing.test.ts
More file actions
99 lines (82 loc) · 2.72 KB
/
debouncing.test.ts
File metadata and controls
99 lines (82 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { noop } from '@algolia/autocomplete-shared';
import userEvent from '@testing-library/user-event';
import { createAutocomplete, InternalAutocompleteSource } from '..';
import { createPlayground, createSource, defer } from '../../../../test/utils';
type Source = InternalAutocompleteSource<{ label: string }>;
const delay = 10;
const debounced = debouncePromise<Source[][], Source[]>(
(items) => Promise.resolve(items),
delay
);
describe('debouncing', () => {
test('only submits the final query', async () => {
const onStateChange = jest.fn();
const getItems = jest.fn(({ query }) => [{ label: query }]);
const { inputElement } = createPlayground(createAutocomplete, {
onStateChange,
getSources: () => debounced([createSource({ getItems })]),
});
userEvent.type(inputElement, 'abc');
await defer(noop, delay);
expect(getItems).toHaveBeenCalledTimes(1);
expect(onStateChange).toHaveBeenLastCalledWith(
expect.objectContaining({
state: expect.objectContaining({
status: 'idle',
isOpen: true,
collections: expect.arrayContaining([
expect.objectContaining({
items: [{ __autocomplete_id: 0, label: 'abc' }],
}),
]),
}),
})
);
});
test('triggers subsequent queries after reopening the panel', async () => {
const onStateChange = jest.fn();
const getItems = jest.fn(({ query }) => [{ label: query }]);
const { inputElement } = createPlayground(createAutocomplete, {
onStateChange,
getSources: () => debounced([createSource({ getItems })]),
});
userEvent.type(inputElement, 'abc{esc}');
expect(onStateChange).toHaveBeenLastCalledWith(
expect.objectContaining({
state: expect.objectContaining({
status: 'idle',
isOpen: false,
}),
})
);
userEvent.type(inputElement, 'def');
await defer(noop, delay);
expect(onStateChange).toHaveBeenLastCalledWith(
expect.objectContaining({
state: expect.objectContaining({
collections: expect.arrayContaining([
expect.objectContaining({
items: [{ __autocomplete_id: 0, label: 'abcdef' }],
}),
]),
status: 'idle',
isOpen: true,
}),
})
);
});
});
function debouncePromise<TParams extends unknown[], TResponse>(
fn: (...params: TParams) => Promise<TResponse>,
time: number
) {
let timerId: ReturnType<typeof setTimeout> | undefined = undefined;
return function (...args: TParams) {
if (timerId) {
clearTimeout(timerId);
}
return new Promise<TResponse>((resolve) => {
timerId = setTimeout(() => resolve(fn(...args)), time);
});
};
}