-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebounce.test.ts
More file actions
97 lines (72 loc) · 2.03 KB
/
Copy pathdebounce.test.ts
File metadata and controls
97 lines (72 loc) · 2.03 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
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { debounce, throttle } from "../../src/utils/debounce.js";
describe("debounce", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("delays execution and only fires the last call", () => {
const fn = vi.fn();
const debounced = debounce(fn, 100);
debounced("a");
debounced("b");
debounced("c");
expect(fn).not.toHaveBeenCalled();
vi.advanceTimersByTime(100);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith("c");
});
it("resets the timer on re-entry", () => {
const fn = vi.fn();
const debounced = debounce(fn, 100);
debounced("first");
vi.advanceTimersByTime(50);
debounced("second");
vi.advanceTimersByTime(50);
expect(fn).not.toHaveBeenCalled();
vi.advanceTimersByTime(50);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith("second");
});
it("fires immediately with zero delay", () => {
const fn = vi.fn();
const debounced = debounce(fn, 0);
debounced("a");
vi.advanceTimersByTime(0);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith("a");
});
});
describe("throttle", () => {
it("limits calls within the interval", () => {
const fn = vi.fn();
const throttled = throttle(fn, 100);
throttled("a");
throttled("b");
throttled("c");
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith("a");
});
it("allows calls after the interval elapses", () => {
const fn = vi.fn();
vi.useFakeTimers();
const throttled = throttle(fn, 100);
throttled("first");
expect(fn).toHaveBeenCalledTimes(1);
vi.advanceTimersByTime(100);
throttled("second");
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenCalledWith("second");
vi.useRealTimers();
});
it("fires on every call with zero interval", () => {
const fn = vi.fn();
const throttled = throttle(fn, 0);
throttled("a");
throttled("b");
throttled("c");
expect(fn).toHaveBeenCalledTimes(3);
});
});