@exadel/esl
Version:
Exadel Smart Library (ESL) is the lightweight custom elements library that provide a set of super-flexible components
64 lines (63 loc) • 2.08 kB
JavaScript
import { ESLEventUtils } from '../../esl-event-listener/core/api';
import { wrap } from '../misc/array';
import { Rect } from '../dom/rect';
let original;
let lastMock;
export class RectMock extends Rect {
constructor(...args) {
if (args.length === 0)
super(0, 0, 0, 0);
else
super(...args);
}
toJSON() {
return this;
}
}
export class IntersectionObserverMock {
constructor(callback) {
this.callback = callback;
this.root = null;
this.rootMargin = '';
this._onObserve = this._onObserve.bind(this);
this.observe = jest.fn(this.observe);
this.unobserve = jest.fn(this.unobserve);
this.disconnect = jest.fn(this.disconnect);
}
get thresholds() {
return [];
}
takeRecords() {
return [];
}
_onObserve(e) {
const entries = wrap(e.detail).map((entry) => IntersectionObserverMock.createEntry(e.target, entry));
this.callback(entries, this);
}
observe(element) {
element.addEventListener('intersection', this._onObserve);
}
unobserve(element) {
element.removeEventListener('intersection', this._onObserve);
}
disconnect() { }
static createEntry(target, init) {
const intersectionRatio = init.intersectionRatio || 0;
return Object.assign({
// Defaults
target, intersectionRect: new RectMock(0, 0, 2000, 2000 * intersectionRatio), rootBounds: new RectMock(0, 0, 2000, 2000), boundingClientRect: new RectMock(0, 0, 2000, 2000), isIntersecting: false, intersectionRatio: 0, time: Date.now() }, init);
}
static trigger($el, detail) {
ESLEventUtils.dispatch($el, 'intersection', { detail });
}
static mock() {
original = window.IntersectionObserver;
window.IntersectionObserver = jest.fn((cb) => (lastMock = new IntersectionObserverMock(cb)));
}
static unmock() {
window.IntersectionObserver = original;
}
static get lastInstance() {
return lastMock;
}
}