|
| 1 | +import '@testing-library/jest-dom/extend-expect' |
| 2 | + |
| 3 | +import { debounce } from './debounce' |
| 4 | + |
| 5 | +describe('debounce', () => { |
| 6 | + beforeEach(() => { |
| 7 | + jest.resetAllMocks() |
| 8 | + jest.useFakeTimers() |
| 9 | + }) |
| 10 | + |
| 11 | + it('returns a debounced function that only gets called after the specified period of time', () => { |
| 12 | + const timeout = 100 |
| 13 | + const testName = 'Billy' |
| 14 | + const testNum = 42 |
| 15 | + const fn = jest.fn((name: string, num: number) => `Hi ${name} ${num}`) |
| 16 | + const debounced = debounce(fn, timeout) |
| 17 | + |
| 18 | + expect(typeof debounced).toBe('function') |
| 19 | + expect(fn).toHaveBeenCalledTimes(0) |
| 20 | + |
| 21 | + debounced(testName, testNum) |
| 22 | + expect(fn).toHaveBeenCalledTimes(0) |
| 23 | + |
| 24 | + // calls a few times and advance timers by "less than timeout" |
| 25 | + jest.advanceTimersByTime(10) |
| 26 | + debounced(testName, testNum) |
| 27 | + jest.advanceTimersByTime(20) |
| 28 | + debounced(testName, testNum) |
| 29 | + jest.advanceTimersByTime(timeout - 1) |
| 30 | + expect(fn).toHaveBeenCalledTimes(0) |
| 31 | + |
| 32 | + // now call, advance to timeout, and ensure it got called and returned correctly |
| 33 | + debounced(testName, testNum) |
| 34 | + jest.advanceTimersByTime(timeout) |
| 35 | + expect(fn).toHaveBeenCalledTimes(1) |
| 36 | + expect(fn).toHaveBeenLastCalledWith(testName, testNum) |
| 37 | + expect(fn).toHaveReturnedWith('Hi Billy 42') |
| 38 | + }) |
| 39 | +}) |
0 commit comments