|
| 1 | +import ScrollSentinel from "$lib/components/ScrollSentinel.svelte"; |
| 2 | +import { layoutContentTopHidden } from "$lib/stores/layout.store"; |
| 3 | +import { render } from "@testing-library/svelte"; |
| 4 | +import { get } from "svelte/store"; |
| 5 | + |
| 6 | +describe("ScrollSentinel", () => { |
| 7 | + let mockObserverInstance: MockIntersectionObserver; |
| 8 | + |
| 9 | + class MockIntersectionObserver implements IntersectionObserver { |
| 10 | + observe: (target: Element) => void = vi.fn(); |
| 11 | + unobserve: (target: Element) => void = vi.fn(); |
| 12 | + disconnect: () => void = vi.fn(); |
| 13 | + takeRecords: () => IntersectionObserverEntry[] = () => []; |
| 14 | + root: Element | Document | null = null; |
| 15 | + rootMargin: string = ""; |
| 16 | + thresholds: ReadonlyArray<number> = []; |
| 17 | + |
| 18 | + constructor(private callback: IntersectionObserverCallback) { |
| 19 | + // eslint-disable-next-line @typescript-eslint/no-this-alias |
| 20 | + mockObserverInstance = this; |
| 21 | + } |
| 22 | + |
| 23 | + // Simulates IntersectionObserver changes |
| 24 | + trigger(entries: Partial<IntersectionObserverEntry>[]) { |
| 25 | + this.callback(entries as IntersectionObserverEntry[], this); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + beforeEach(() => { |
| 30 | + vi.spyOn(global, "IntersectionObserver").mockImplementation( |
| 31 | + (callback) => new MockIntersectionObserver(callback), |
| 32 | + ); |
| 33 | + }); |
| 34 | + |
| 35 | + afterEach(() => { |
| 36 | + vi.restoreAllMocks(); |
| 37 | + }); |
| 38 | + |
| 39 | + it("should render a sentinel element", () => { |
| 40 | + const { container } = render(ScrollSentinel); |
| 41 | + expect(container.querySelector("[data-tid='sentinel']")).not.toBeNull(); |
| 42 | + }); |
| 43 | + |
| 44 | + it("should update the store on intersection", () => { |
| 45 | + expect(get(layoutContentTopHidden)).toBe(false); |
| 46 | + |
| 47 | + mockObserverInstance.trigger([{ isIntersecting: false }]); |
| 48 | + expect(get(layoutContentTopHidden)).toBe(true); |
| 49 | + |
| 50 | + mockObserverInstance.trigger([{ isIntersecting: true }]); |
| 51 | + expect(get(layoutContentTopHidden)).toBe(false); |
| 52 | + }); |
| 53 | +}); |
0 commit comments