Skip to content
Advertisement

Testing code that uses an IntersectionObserver

I have a 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:

JavaScript

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 (ideally not using jQuery)?

Advertisement

Answer

Here’s another alternative based on previous answers, you can run it inside the beforeEach methods, or at the beginning of the .test.js file.

You could also pass parameters to the setupIntersectionObserverMock to mock the observe and/or unobserve methods to spy on them with a jest.fn() mock function.

JavaScript

And for TypeScript:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement