-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuse-hover.test.ts
63 lines (51 loc) · 1.8 KB
/
use-hover.test.ts
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
import { act, renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { useHover } from './use-hover';
describe('useHover', () => {
it('should return isHovered as false initially', () => {
const ref = { current: document.createElement('div') };
const { result } = renderHook(() => useHover(ref));
expect(result.current.isHovered).toBe(false);
});
it('should set isHovered to true on mouseenter and false on mouseleave', () => {
const ref = { current: document.createElement('div') };
const { result } = renderHook(() => useHover(ref));
act(() => {
ref.current.dispatchEvent(
new MouseEvent('mouseenter', { bubbles: true })
);
});
expect(result.current.isHovered).toBe(true);
act(() => {
ref.current.dispatchEvent(
new MouseEvent('mouseleave', { bubbles: true })
);
});
expect(result.current.isHovered).toBe(false);
});
it('should clean up event listeners on unmount using abort signal', () => {
const ref = { current: document.createElement('div') };
const addEventListenerSpy = vi.spyOn(ref.current, 'addEventListener');
const controllerSpy = vi.spyOn(AbortController.prototype, 'abort');
const { unmount } = renderHook(() => useHover(ref));
expect(addEventListenerSpy).toHaveBeenCalledWith(
'mouseenter',
expect.any(Function),
expect.objectContaining({
passive: true,
signal: expect.any(AbortSignal)
})
);
expect(addEventListenerSpy).toHaveBeenCalledWith(
'mouseleave',
expect.any(Function),
expect.objectContaining({
passive: true,
signal: expect.any(AbortSignal)
})
);
unmount();
expect(controllerSpy).toHaveBeenCalledTimes(1);
controllerSpy.mockRestore();
});
});