我們這次的測試目標只有兩個
測試當元件掛載(mount)時,IntersectionObserver
是否開始觀察(observe)正確的目標元素。測試中使用 renderHook
來渲染 hook,並檢查 observe
方法是否被用正確的參數調用,即用 ref.current
作為參數調用,其中 ref.current
是一個 div
元素。
測試當元件卸載(unmount)時,IntersectionObserver
是否停止觀察(unobserve)正確的目標元素。測試中使用 unmount
函數來模擬元件的卸載,並檢查 unobserve
方法是否被用正確的參數調用。
測試:
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);
});
});