-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathscroll-into-view-mock.js
72 lines (61 loc) · 2 KB
/
scroll-into-view-mock.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { find } from '@ember/test-helpers';
export default function mockScrollIntoView() {
let elementsInvokedOn = [];
let mockScrollIntoViewFunction = function () {
elementsInvokedOn.push(this);
};
let mockScrollToElementWithOffsetFunction = function (options) {
elementsInvokedOn.push(options);
};
// manually mocking native function
let preExistingScrollIntoViewFunction =
window.Element.prototype.scrollIntoView;
let preExistingScrollToFunction = window.scrollTo;
window.Element.prototype.scrollIntoView = mockScrollIntoViewFunction;
window.scrollTo = mockScrollToElementWithOffsetFunction;
// helper fuctions that will be returned
let scrollIntoViewCalledWith = (selector, options = {}) => {
let element;
// check if it's a string and get the object
if (typeof selector === 'string') {
element = find(selector);
} else {
// element was passed in
element = selector;
}
if (options?.topOffset === undefined && options?.leftOffset === undefined) {
return elementsInvokedOn.includes(element);
}
if (!element || !document) {
return;
}
const { behavior = 'smooth', leftOffset, topOffset } = options;
const elementLeft =
leftOffset === undefined
? 0
: element.getBoundingClientRect().left -
document.body.getBoundingClientRect().left -
leftOffset;
const elementTop =
topOffset === undefined
? 0
: element.getBoundingClientRect().top -
document.body.getBoundingClientRect().top -
topOffset;
return elementsInvokedOn.some((calledOptions) => {
return (
behavior === calledOptions.behavior &&
elementTop === calledOptions.top &&
elementLeft === calledOptions.left
);
});
};
let resetMock = () => {
window.Element.prototype.scrollIntoView = preExistingScrollIntoViewFunction;
window.scrollTo = preExistingScrollToFunction;
};
return {
scrollIntoViewCalledWith,
resetMock,
};
}