[Day 22] useIntersectionObserver監控畫面

 
我本來想要講解IntersectionObserver這個api的,但是我覺得莫力全前輩之前寫的文章更好,所以決定直接放他的文章連結,他講解得非常清楚,如果不知道這個是什麼web api,歡迎去看,關於IntersectionObserver他寫在文章的中後段
接下來就能使用了,用一個簡單的範例來寫,實際上可能會更複雜,例如你可能會需要換頁,再call api加資料等,像FB那樣infinite scroll,這邊就做一個簡單版的
這樣就看起來是沒問題的
 
import { renderHook, act } from "@testing-library/react";
import { useRef } from "react";
import { useIntersectionObserver } from "../src";
describe('useIntersectionObserver', () => {
let observe: jest.Mock;
let unobserve: jest.Mock;
let disconnect: jest.Mock;
beforeEach(() => {
observe = jest.fn();
unobserve = jest.fn();
disconnect = jest.fn();
// @ts-ignore
window.IntersectionObserver = jest.fn(() => ({
observe,
unobserve,
disconnect,
}));
});
it('should observe the target element on mount', () => {
const { result } = renderHook(() => {
const ref = { current: document.createElement('div') };
const isIntersecting = useIntersectionObserver(ref);
return { ref, isIntersecting };
});
expect(observe).toHaveBeenCalledWith(result.current.ref.current);
});
it('should unobserve the target element on unmount', () => {
const { result, unmount } = renderHook(() => {
const ref = { current: document.createElement('div') };
const isIntersecting = useIntersectionObserver(ref);
return { ref, isIntersecting };
});
act(() => {
unmount();
});
expect(unobserve).toHaveBeenCalledWith(result.current.ref.current);
});
});