Skip to content

Commit 595dfcc

Browse files
committed
test: add unit tests for useInView hook
1 parent 1f79b71 commit 595dfcc

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

tests/useInView.spec.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest'
2+
import { mount } from '@vue/test-utils'
3+
import { defineComponent, h, nextTick, ref } from 'vue'
4+
import { useInView } from '../packages/motion/src/utils/use-in-view'
5+
6+
// Mock IntersectionObserver
7+
const mockIntersectionObserver = vi.fn()
8+
mockIntersectionObserver.mockReturnValue({
9+
observe: () => null,
10+
unobserve: () => null,
11+
disconnect: () => null,
12+
})
13+
window.IntersectionObserver = mockIntersectionObserver
14+
15+
// Mock inView from framer-motion
16+
vi.mock('framer-motion/dom', () => ({
17+
inView: (element: Element, onStart: Function, options = {}) => {
18+
// Simulate the callback being called
19+
const cleanup = onStart()
20+
return () => {
21+
if (cleanup)
22+
cleanup()
23+
}
24+
},
25+
}))
26+
27+
describe('useInView', () => {
28+
beforeEach(() => {
29+
vi.clearAllMocks()
30+
})
31+
32+
it('should return a ref with initial value of false and update to true when element enters viewport', async () => {
33+
const TestComponent = defineComponent({
34+
setup() {
35+
const elementRef = ref<HTMLDivElement | null>(null)
36+
const isInView = useInView(elementRef)
37+
return { isInView, elementRef }
38+
},
39+
render() {
40+
return h('div', { ref: 'elementRef' })
41+
},
42+
})
43+
44+
const wrapper = mount(TestComponent)
45+
expect(wrapper.vm.isInView).toBe(false)
46+
await nextTick()
47+
expect(wrapper.vm.isInView).toBe(true)
48+
})
49+
})

0 commit comments

Comments
 (0)