I have a (rather poorly written) javascript component in my application that handles infinite scroll pagination, and i'm trying to rewrite it to use the IntersectionObserver
, as described here, however i'm having issues in testing it.
Is there a way to drive the behavior of the observer in a QUnit test, i.e. to trigger the observer callback with some entries described in my tests?
A possible solution I have come up with is to expose the callback function in the component's prototype and to invoke it directly in my test, something like this:
InfiniteScroll.prototype.observerCallback = function(entries) { //handle the infinite scroll } InfiniteScroll.prototype.initObserver = function() { var io = new IntersectionObserver(this.observerCallback); io.observe(someElements); } //In my test var component = new InfiniteScroll(); component.observerCallback(someEntries); //Do some assertions about the state after the callback has been executed
I don't really like this approach since it's exposing the fact that the component uses an IntersectionObserver
internally, which is an implementation detail that in my opinion should not be visible to client code, so is there any better way to test this?
Bonus love for solutions not using jQuery :)
The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount.
To use Intersection Observer, we need to first create a new observer, which takes two parameters: An object with the observer's options, and the callback function that we want to execute whenever the element we're observing (known as the observer target) intersects with the root (the scrolling container, which must be ...
isIntersecting. The IntersectionObserverEntry interface's read-only isIntersecting property is a Boolean value which is true if the target element intersects with the intersection observer's root.
useIntersectionObserver() This React Hook detects visibility of a component on the viewport using the IntersectionObserver API natively present in the browser. It can be very useful to lazy-loading of images, implementing "infinite scrolling" or starting animations for example.
In your jest.setup.js file, mock the IntersectionObserver with the following implementation:
global.IntersectionObserver = class IntersectionObserver { constructor() {} disconnect() { return null; } observe() { return null; } takeRecords() { return null; } unobserve() { return null; } };
Instead of using the Jest Setup File, you can do this mocking also directly in your tests or in your beforeAll,beforeEach blocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With