const intersectionObserverMock = {callback: null, observedTargets: []};
export function mockIntersectionObserver() {
intersectionObserverMock.callback = null;
intersectionObserverMock.observedTargets = [];
class IntersectionObserver {
constructor() {
intersectionObserverMock.callback = arguments[0];
}
disconnect() {
intersectionObserverMock.callback = null;
intersectionObserverMock.observedTargets.splice(0);
}
observe(target) {
intersectionObserverMock.observedTargets.push(target);
}
unobserve(target) {
const index = intersectionObserverMock.observedTargets.indexOf(target);
if (index >= 0) {
intersectionObserverMock.observedTargets.splice(index, 1);
}
}
}
window.IntersectionObserver = IntersectionObserver;
return intersectionObserverMock;
}
export function simulateIntersection(...entries) {
intersectionObserverMock.callback(
entries.map(([target, rect, ratio]) => ({
boundingClientRect: {
top: rect.y,
left: rect.x,
width: rect.width,
height: rect.height,
},
intersectionRatio: ratio,
target,
})),
);
}
export function setBoundingClientRect(target, {x, y, width, height}) {
target.getBoundingClientRect = function () {
return {
width,
height,
left: x,
right: x + width,
top: y,
bottom: y + height,
};
};
}
export function setClientRects(target, rects) {
target.getClientRects = function () {
return rects.map(({x, y, width, height}) => ({
width,
height,
left: x,
right: x + width,
top: y,
bottom: y + height,
x,
y,
}));
};
}