【发布时间】:2020-12-09 17:24:01
【问题描述】:
我有一个使用相交观察器的组件,并且想以开玩笑的方式测试元素是否相交的效果。我已经设法像在这个答案中那样模拟 Intersection Observer:https://stackoverflow.com/a/58651649/4716214
现在我想在特定元素处“伪造回调”isIntersecting 触发器。是否可以在测试中模拟这个?
const observe = jest.fn();
const disconnect = jest.fn();
setupIntersectionObserverMock({ observe: observe, disconnect: disconnect });
const page = await newSpecPage({
components: [TestComponent],
html: `<div></div>`, // This is the element I want to trigger an "isIntersecting" on
});
export const setupIntersectionObserverMock = ({
root = null,
rootMargin = '',
thresholds = [],
disconnect = () => null,
observe = () => null,
takeRecords = () => null,
unobserve = () => null,
} = {}): void => {
class MockIntersectionObserver implements IntersectionObserver {
readonly root: Element | null = root;
readonly rootMargin: string = rootMargin;
readonly thresholds: ReadonlyArray<number> = thresholds;
disconnect: () => void = disconnect;
observe: (target: Element) => void = observe;
takeRecords: () => IntersectionObserverEntry[] = takeRecords;
unobserve: (target: Element) => void = unobserve;
}
Object.defineProperty(window, 'IntersectionObserver', {
writable: true,
configurable: true,
value: MockIntersectionObserver,
});
Object.defineProperty(global, 'IntersectionObserver', {
writable: true,
configurable: true,
value: MockIntersectionObserver,
});
};
【问题讨论】:
标签: jestjs intersection-observer