|
| 1 | +import { fireEvent, render } from '@testing-library/react'; |
| 2 | +import useFocus from './useFocus'; |
| 3 | +import React from 'react'; |
| 4 | + |
| 5 | +interface Entrie { |
| 6 | + target: Element; |
| 7 | + isIntersecting: boolean; |
| 8 | +} |
| 9 | + |
| 10 | +const mockIntersectionObserver = class { |
| 11 | + entries: Entrie[]; |
| 12 | + constructor(callback) { |
| 13 | + this.entries = []; |
| 14 | + window.addEventListener('scroll', () => { |
| 15 | + if (window.scrollY > 50) { |
| 16 | + this.entries.map((entry) => { |
| 17 | + entry.isIntersecting = this.isInViewPort(); |
| 18 | + }); |
| 19 | + } |
| 20 | + callback(this.entries, this); |
| 21 | + }); |
| 22 | + } |
| 23 | + |
| 24 | + isInViewPort() { |
| 25 | + return true; |
| 26 | + } |
| 27 | + |
| 28 | + observe(target: Element) { |
| 29 | + this.entries.push({ isIntersecting: false, target }); |
| 30 | + } |
| 31 | + |
| 32 | + unobserve(target) { |
| 33 | + this.entries = this.entries.filter((ob) => ob.target !== target); |
| 34 | + } |
| 35 | + |
| 36 | + disconnect() { |
| 37 | + this.entries = []; |
| 38 | + } |
| 39 | +}; |
| 40 | + |
| 41 | +describe('useFocus 기능 테스트', () => { |
| 42 | + beforeEach(() => { |
| 43 | + // eslint-disable-next-line |
| 44 | + global.IntersectionObserver = mockIntersectionObserver as any; |
| 45 | + }); |
| 46 | + |
| 47 | + it('focus되었을때 onFocusCallback을 실행시킬 수 있다.', async () => { |
| 48 | + const mock = jest.fn(); |
| 49 | + const Test = () => { |
| 50 | + const ref = useFocus<HTMLDivElement>(mock); |
| 51 | + return <div ref={ref}>Test</div>; |
| 52 | + }; |
| 53 | + render(<Test />); |
| 54 | + fireEvent.scroll(window, { target: { scrollY: 100 } }); |
| 55 | + expect(mock).toHaveBeenCalled(); |
| 56 | + }); |
| 57 | +}); |
0 commit comments