Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion src/__tests__/useInView.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { render, screen } from "@testing-library/react";
import { act, render, screen } from "@testing-library/react";
import React, { useCallback } from "react";
import { defaultFallbackInView, type IntersectionOptions } from "../index";
import {
Expand Down Expand Up @@ -118,6 +118,38 @@ test("should respect trigger once", () => {
getByText("true");
});

test("should respect the threshold before triggering once", () => {
const { getByTestId, getByText } = render(
<HookComponent
options={{ initialInView: true, threshold: 0.5, triggerOnce: true }}
/>,
);
const wrapper = getByTestId("wrapper");
const instance = intersectionMockInstance(wrapper);
const callback = vi.mocked(window.IntersectionObserver).mock.calls[0][0];
const createEntry = (
intersectionRatio: number,
): IntersectionObserverEntry => ({
boundingClientRect: wrapper.getBoundingClientRect(),
intersectionRatio,
intersectionRect: wrapper.getBoundingClientRect(),
isIntersecting: true,
rootBounds: null,
target: wrapper,
time: performance.now(),
});

act(() => callback([createEntry(0.25)], instance));

getByText("false");
expect(instance.unobserve).not.toHaveBeenCalled();

act(() => callback([createEntry(0.5)], instance));

getByText("true");
expect(instance.unobserve).toHaveBeenCalledTimes(1);
});

test("should trigger onChange", () => {
const onChange = vi.fn();
render(<HookComponent options={{ onChange }} />);
Expand Down
2 changes: 1 addition & 1 deletion src/useInView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export function useInView({
});
if (callback.current) callback.current(inView, entry);

if (entry.isIntersecting && triggerOnce && unobserve) {
if (inView && triggerOnce && unobserve) {
// If it should only trigger once, unobserve the element after it's inView
unobserve();
unobserve = undefined;
Expand Down
Loading