Skip to content
Open
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
2 changes: 1 addition & 1 deletion src/useIntersection.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { RefObject, useEffect, useState } from 'react';

const useIntersection = (
ref: RefObject<HTMLElement>,
ref: RefObject<HTMLElement | null>,
options: IntersectionObserverInit
): IntersectionObserverEntry | null => {
const [intersectionObserverEntry, setIntersectionObserverEntry] =
Expand Down
44 changes: 41 additions & 3 deletions tests/useIntersection.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import TestUtils from 'react-dom/test-utils';
import TestRenderer from 'react-test-renderer';
import { intersectionObserver } from '@shopify/jest-dom-mocks';
import { renderHook } from '@testing-library/react-hooks';
import { useIntersection } from '../src';
import useIntersection from '../src/useIntersection';

beforeEach(() => {
intersectionObserver.mock();
Expand Down Expand Up @@ -43,10 +43,48 @@ describe('useIntersection', () => {
});

it('should return null if a ref without a current value is provided', () => {
targetRef = createRef();
const emptyRef = createRef<HTMLDivElement>();

const { result } = renderHook(() => useIntersection(emptyRef, { root: null, threshold: 1 }));
expect(result.current).toBe(null);
});

it('should accept a ref initialized with null', () => {
const { result } = renderHook(() => {
const ref = React.useRef(null);
return useIntersection(ref, {});
});

const { result } = renderHook(() => useIntersection(targetRef, { root: null, threshold: 1 }));
expect(result.current).toBe(null);
expect(intersectionObserver.observers).toHaveLength(0);
});

it('should observe and disconnect an explicitly nullable element ref', () => {
const { result, rerender, unmount } = renderHook(() => {
const ref = React.useRef<HTMLDivElement | null>(null);
const entry = useIntersection(ref, {});
return { ref, entry };
});
const element = document.createElement('div');

expect(result.current.entry).toBe(null);
expect(intersectionObserver.observers).toHaveLength(0);

result.current.ref.current = element;
rerender();

expect(intersectionObserver.observers).toHaveLength(1);
expect(intersectionObserver.observers[0].target).toBe(element);

result.current.ref.current = null;
rerender();

expect(result.current.entry).toBe(null);
expect(IntersectionObserver.prototype.disconnect).toHaveBeenCalledTimes(1);

unmount();

expect(IntersectionObserver.prototype.disconnect).toHaveBeenCalledTimes(1);
});

it('should reset an intersectionObserverEntry when the ref changes', () => {
Expand Down