If we use jest with typescript, which have an intersection observer used, the mocking of intersection observer will become hard. So far I'm at:
beforeEach(() => {
// IntersectionObserver isn't available in test environment
const mockIntersectionObserver = class {
observe() {
console.log(this);
}
unobserve() {
console.log(this);
}
disconnect() {
console.log(this);
}
root = null
rootMargin = '0'
thresholds=[1]
takeRecords=() => ([{
isIntersecting: true,
boundingClientRect: true,
intersectionRatio: true,
intersectionRect: true,
rootBounds: true,
target: true,
time: true,
}])
};
window.IntersectionObserver = mockIntersectionObserver;
});
But still this is throwing error like:
Type 'typeof mockIntersectionObserver' is not assignable to type '{ new (callback: IntersectionObserverCallback, options?: IntersectionObserverInit | undefined): IntersectionObserver; prototype: IntersectionObserver; }'.
The types returned by 'prototype.takeRecords()' are incompatible between these types.
Type '{ isIntersecting: boolean; boundingClientRect: boolean; intersectionRatio: boolean; intersectionRect: boolean; rootBounds: boolean; target: boolean; time: boolean; }[]' is not assignable to type 'IntersectionObserverEntry[]'.
Type '{ isIntersecting: boolean; boundingClientRect: boolean; intersectionRatio: boolean; intersectionRect: boolean; rootBounds: boolean; target: boolean; time: boolean; }' is not assignable to type 'IntersectionObserverEntry'.
Types of property 'boundingClientRect' are incompatible.
Type 'boolean' is not assignable to type 'DOMRectReadOnly'.ts(2322
I can keep adding correct types to each element, but is there a better way?
How can I add an intersection observer to the jest environment? I think it will be better than mocking like this.