-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuse-window-scroll.test.ts
91 lines (71 loc) · 2.27 KB
/
use-window-scroll.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
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
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useWindowScroll } from './use-window-scroll';
describe('useWindowScroll', () => {
beforeEach(() => {
// Reset the scroll position before each test
window.scrollX = 0;
window.scrollY = 0;
});
it('should return the initial position of { x: 0, y: 0 }', () => {
const { result } = renderHook(() => useWindowScroll());
const [position] = result.current;
expect(position).toEqual({ x: 0, y: 0 });
});
it('should update position on scroll', () => {
const { result } = renderHook(() => useWindowScroll());
act(() => {
// Simulate scrolling
window.scrollX = 50;
window.scrollY = 100;
window.dispatchEvent(new Event('scroll'));
});
const [position] = result.current;
expect(position).toEqual({ x: 50, y: 100 });
});
it('should update position on resize', () => {
const { result } = renderHook(() => useWindowScroll());
act(() => {
// Simulate resizing (positions can remain the same)
window.scrollX = 30;
window.scrollY = 60;
window.dispatchEvent(new Event('resize'));
});
const [position] = result.current;
expect(position).toEqual({ x: 30, y: 60 });
});
it('should call window.scrollTo with the correct arguments', () => {
// Mock scrollTo function
const scrollToMock = vi.fn();
Object.defineProperty(window, 'scrollTo', {
value: scrollToMock,
writable: true
});
const { result } = renderHook(() => useWindowScroll());
const [, scrollTo] = result.current;
act(() => {
scrollTo({ y: 200, x: 100 });
});
expect(scrollToMock).toHaveBeenCalledWith({
top: 200,
left: 100,
behavior: 'smooth'
});
});
it('should call window.scrollTo with custom behavior', () => {
const scrollToMock = vi.fn();
Object.defineProperty(window, 'scrollTo', {
value: scrollToMock,
writable: true
});
const { result } = renderHook(() => useWindowScroll());
const [, scrollTo] = result.current;
act(() => {
scrollTo({ y: 300 }, { behavior: 'auto' });
});
expect(scrollToMock).toHaveBeenCalledWith({
top: 300,
behavior: 'auto'
});
});
});