Skip to content

Commit

Permalink
test: ScrollSentinel
Browse files Browse the repository at this point in the history
  • Loading branch information
mstrasinskis committed Feb 18, 2025
1 parent eec4965 commit fd19c41
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/lib/components/ScrollSentinel.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { isNullish } from "@dfinity/utils";
import { onDestroy, onMount } from "svelte";
// The ScrollSentinel component should be placed right before the scrollable content
// The ScrollSentinel component should be placed right before the content
// inside the scrollable container.
export let scrollContainer: HTMLElement;
Expand All @@ -20,4 +20,4 @@
});
</script>

<div bind:this={element}></div>
<div data-tid="sentinel" bind:this={element}></div>
53 changes: 53 additions & 0 deletions src/tests/lib/components/ScrollSentinel.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import ScrollSentinel from "$lib/components/ScrollSentinel.svelte";
import { layoutContentTopHidden } from "$lib/stores/layout.store";
import { render } from "@testing-library/svelte";
import { get } from "svelte/store";

describe("ScrollSentinel", () => {
let mockObserverInstance: MockIntersectionObserver;

class MockIntersectionObserver implements IntersectionObserver {
observe: (target: Element) => void = vi.fn();
unobserve: (target: Element) => void = vi.fn();
disconnect: () => void = vi.fn();
takeRecords: () => IntersectionObserverEntry[] = () => [];
root: Element | Document | null = null;
rootMargin: string = "";
thresholds: ReadonlyArray<number> = [];

constructor(private callback: IntersectionObserverCallback) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
mockObserverInstance = this;
}

// Simulates IntersectionObserver changes
trigger(entries: Partial<IntersectionObserverEntry>[]) {
this.callback(entries as IntersectionObserverEntry[], this);
}
}

beforeEach(() => {
vi.spyOn(global, "IntersectionObserver").mockImplementation(
(callback) => new MockIntersectionObserver(callback),
);
});

afterEach(() => {
vi.restoreAllMocks();
});

it("should render a sentinel element", () => {
const { container } = render(ScrollSentinel);
expect(container.querySelector("[data-tid='sentinel']")).not.toBeNull();
});

it("should update the store on intersection", () => {
expect(get(layoutContentTopHidden)).toBe(false);

mockObserverInstance.trigger([{ isIntersecting: false }]);
expect(get(layoutContentTopHidden)).toBe(true);

mockObserverInstance.trigger([{ isIntersecting: true }]);
expect(get(layoutContentTopHidden)).toBe(false);
});
});

0 comments on commit fd19c41

Please sign in to comment.