This releases is focused on helping you when writing tests.
In order to write meaningful tests, the IntersectionObserver needs to be
mocked. If you are writing your tests in Jest, you can use the included
test-utils.js. It mocks the IntersectionObserver, and includes a few methods
to assist with faking the inView state.
test-utils.js
Import the methods from react-intersection-observer/test-utils.
mockAllIsIntersecting(isIntersecting:boolean)
Set the isIntersecting on all current IntersectionObserver instances.
mockIsIntersecting(element:Element, isIntersecting:boolean)
Set the isIntersecting for the IntersectionObserver of a specific element.
intersectionMockInstance(element:Element): IntersectionObserver
Call the intersectionMockInstance method with an element, to get the (mocked)
IntersectionObserver instance. You can use this to spy on the observe and
unobserve methods.
Test Example
import React from 'react'
import { render } from 'react-testing-library'
import { useInView } from 'react-intersection-observer'
import { mockAllIsIntersecting } from 'react-intersection-observer/test-utils'
const HookComponent = ({ options }) => {
const [ref, inView] = useInView(options)
return <div ref={ref}>{inView.toString()}</div>
}
test('should create a hook inView', () => {
const { getByText } = render(<HookComponent />)
mockAllIsIntersecting(true)
getByText('true')
})