Debounce_test.res

 1open VitestHelpers
 2
 3@module("vitest") @val external vi: 'a = "vi"
 4
 5describe("Debounce", () => {
 6  testAsync("function is called after delay when created with make", async t => {
 7    let mockFn = vi["fn"]()
 8    let _handle = Debounce.make(mockFn, 50)
 9
10    // Function should not be called immediately
11    t->expect(mockFn["mock"]["calls"]->Array.length)->toEqual(0)
12
13    // Wait for delay
14    await (%raw(`new Promise(r => setTimeout(r, 60))`): promise<unit>)
15
16    // Now it should be called
17    t->expect(mockFn["mock"]["calls"]->Array.length)->toEqual(1)
18  })
19
20  testAsync("cancel prevents function from being called", async t => {
21    let mockFn = vi["fn"]()
22    let handle = Debounce.make(mockFn, 50)
23
24    // Cancel before delay
25    handle->Debounce.cancel
26
27    // Wait for original delay
28    await (%raw(`new Promise(r => setTimeout(r, 60))`): promise<unit>)
29
30    // Should not be called since it was cancelled
31    t->expect(mockFn["mock"]["calls"]->Array.length)->toEqual(0)
32  })
33
34  testAsync("cancel is safe to call multiple times", async t => {
35    let mockFn = vi["fn"]()
36    let handle = Debounce.make(mockFn, 50)
37
38    // Cancel multiple times
39    handle->Debounce.cancel
40    handle->Debounce.cancel
41    handle->Debounce.cancel
42
43    // Wait for original delay
44    await (%raw(`new Promise(r => setTimeout(r, 60))`): promise<unit>)
45
46    // Should not be called
47    t->expect(mockFn["mock"]["calls"]->Array.length)->toEqual(0)
48  })
49
50  testAsync("cancel is safe to call after function already executed", async t => {
51    let mockFn = vi["fn"]()
52    let handle = Debounce.make(mockFn, 50)
53
54    // Wait for it to execute
55    await (%raw(`new Promise(r => setTimeout(r, 60))`): promise<unit>)
56
57    // Should be called once
58    t->expect(mockFn["mock"]["calls"]->Array.length)->toEqual(1)
59
60    // Cancel after execution should be safe (no-op)
61    handle->Debounce.cancel
62
63    // Still only called once
64    t->expect(mockFn["mock"]["calls"]->Array.length)->toEqual(1)
65  })
66
67  testAsync("creating new debounce and cancelling old one works", async t => {
68    let mockFn1 = vi["fn"]()
69    let mockFn2 = vi["fn"]()
70    
71    let handle1 = Debounce.make(mockFn1, 50)
72
73    // Cancel first and create second before first delay completes
74    handle1->Debounce.cancel
75    let _handle2 = Debounce.make(mockFn2, 50)
76
77    // Wait for delay
78    await (%raw(`new Promise(r => setTimeout(r, 60))`): promise<unit>)
79
80    // First should not be called (cancelled), second should be called
81    t->expect(mockFn1["mock"]["calls"]->Array.length)->toEqual(0)
82    t->expect(mockFn2["mock"]["calls"]->Array.length)->toEqual(1)
83  })
84})