1 import debounce from './debounce';
3 describe('debounce()', () => {
16 it('delays invoking function until after wait time', () => {
17 const functionToDebounce = jest.fn();
19 const debouncedFunction = debounce(functionToDebounce, wait);
22 expect(functionToDebounce).not.toHaveBeenCalled();
24 // Call function again just before the wait time expires
25 jest.advanceTimersByTime(wait - 1);
27 expect(functionToDebounce).not.toHaveBeenCalled();
29 // fast-forward time until 1 millisecond before the function should be invoked
30 jest.advanceTimersByTime(wait - 1);
31 expect(functionToDebounce).not.toHaveBeenCalled();
33 // fast-forward until 1st call should be executed
34 jest.advanceTimersByTime(1);
35 expect(functionToDebounce).toHaveBeenCalledTimes(1);
38 it('does not invoke function if already invoked', () => {
39 const functionToDebounce = jest.fn();
41 const debouncedFunction = debounce(functionToDebounce, wait);
45 jest.advanceTimersByTime(wait);
46 expect(functionToDebounce).toHaveBeenCalledTimes(1);
47 functionToDebounce.mockClear();
49 jest.advanceTimersByTime(wait);
50 expect(functionToDebounce).not.toHaveBeenCalled();
53 describe('options', () => {
54 describe('immediate', () => {
55 it('defaults to false and does not invoke function immediately', () => {
56 const functionToDebounce = jest.fn();
58 const debouncedFunction = debounce(functionToDebounce, wait);
61 expect(functionToDebounce).not.toHaveBeenCalled();
64 it('invokes function immediately if true', () => {
65 const functionToDebounce = jest.fn();
67 const debouncedFunction = debounce(functionToDebounce, wait, { leading: true });
70 expect(functionToDebounce).toHaveBeenCalled();
75 describe('abort()', () => {
76 it('does not invoke function if abort is called before wait time expires', () => {
77 const functionToDebounce = jest.fn();
79 const debouncedFunction = debounce(functionToDebounce, wait);
83 // Call function again just before the wait time expires
84 jest.advanceTimersByTime(wait - 1);
85 debouncedFunction.cancel();
87 // fast-forward until 1st call should be executed
88 jest.advanceTimersByTime(1);
89 expect(functionToDebounce).not.toHaveBeenCalled();