-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdebounce_test.ts
More file actions
86 lines (66 loc) · 1.83 KB
/
debounce_test.ts
File metadata and controls
86 lines (66 loc) · 1.83 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
import { assertEquals } from "@std/assert";
import { delay } from "@std/async/delay";
import { FakeTime } from "@std/testing/time";
import { debounce } from "./debounce.ts";
Deno.test("debounce", async (t) => {
await t.step("delays function execution", async () => {
using time = new FakeTime();
let callCount = 0;
const fn = debounce(() => {
callCount++;
}, { delay: 100 });
fn();
assertEquals(callCount, 0);
await time.tickAsync(50);
assertEquals(callCount, 0);
await time.tickAsync(50);
assertEquals(callCount, 1);
});
await t.step(
"cancels previous calls when called multiple times",
async () => {
using time = new FakeTime();
let callCount = 0;
let lastValue = 0;
const fn = debounce((value: number) => {
callCount++;
lastValue = value;
}, { delay: 100 });
fn(1);
await time.tickAsync(50);
fn(2);
await time.tickAsync(50);
fn(3);
await time.tickAsync(50);
assertEquals(callCount, 0);
await time.tickAsync(50);
assertEquals(callCount, 1);
assertEquals(lastValue, 3);
},
);
await t.step("works with real timers", async () => {
let callCount = 0;
const fn = debounce(() => {
callCount++;
}, { delay: 50 });
fn();
assertEquals(callCount, 0);
await delay(30);
assertEquals(callCount, 0);
await delay(30);
assertEquals(callCount, 1);
});
await t.step("respects abort signal", async () => {
using time = new FakeTime();
let callCount = 0;
const controller = new AbortController();
const fn = debounce(() => {
callCount++;
}, { delay: 100, signal: controller.signal });
fn();
await time.tickAsync(50);
controller.abort();
await time.tickAsync(100);
assertEquals(callCount, 0);
});
});