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 :)
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.