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
9 changes: 4 additions & 5 deletions src/useScrolling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const useScrolling = (ref: RefObject<HTMLElement>): boolean => {
const [scrolling, setScrolling] = useState<boolean>(false);

useEffect(() => {
if (ref.current) {
const element = ref.current;
if (element) {
let scrollingTimeout;

const handleScrollEnd = () => {
Expand All @@ -18,11 +19,9 @@ const useScrolling = (ref: RefObject<HTMLElement>): boolean => {
scrollingTimeout = setTimeout(() => handleScrollEnd(), 150);
};

on(ref.current, 'scroll', handleScroll, false);
on(element, 'scroll', handleScroll, false);
return () => {
if (ref.current) {
off(ref.current, 'scroll', handleScroll, false);
}
off(element, 'scroll', handleScroll, false);
};
}
return () => {};
Expand Down
32 changes: 32 additions & 0 deletions tests/useScrolling.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { renderHook } from '@testing-library/react-hooks';
import useScrolling from '../src/useScrolling';

describe('useScrolling', () => {
it('removes the listener from the element it originally observed', () => {
const element = document.createElement('div');
const replacement = document.createElement('div');
const removeListener = jest.spyOn(element, 'removeEventListener');
const removeReplacementListener = jest.spyOn(replacement, 'removeEventListener');
const ref = { current: element };

const { unmount } = renderHook(() => useScrolling(ref));

ref.current = replacement;
unmount();

expect(removeListener).toHaveBeenCalledWith('scroll', expect.any(Function), false);
expect(removeReplacementListener).not.toHaveBeenCalled();
});

it('removes the listener when the ref has been cleared', () => {
const element = document.createElement('div');
const removeListener = jest.spyOn(element, 'removeEventListener');
const ref: { current: HTMLElement | null } = { current: element };
const { unmount } = renderHook(() => useScrolling(ref));

ref.current = null;
unmount();

expect(removeListener).toHaveBeenCalledWith('scroll', expect.any(Function), false);
});
});