-
Notifications
You must be signed in to change notification settings - Fork 77
/
utils.ts
523 lines (468 loc) · 16.2 KB
/
utils.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
// @ts-strict-ignore
import { BoundingBox, ElementHandle } from "puppeteer";
import { LuminaJsx } from "@arcgis/lumina";
import { newE2EPage, E2EPage, E2EElement } from "@arcgis/lumina-compiler/puppeteerTesting";
import { expect } from "vitest";
import { ComponentTag } from "./commonTests/interfaces";
/** Util to help type global props for testing. */
export type GlobalTestProps<T> = T & Window & typeof globalThis;
type FilterPropsByPropertyName<T, PropName extends string> = {
[K in keyof T]: PropName extends keyof T[K] ? T[K] : never;
};
/** Helper to extract a type by filtering the type by the property name. */
export type IntrinsicElementsWithProp<T extends string> = FilterPropsByPropertyName<
LuminaJsx.IntrinsicElements,
T
>[keyof FilterPropsByPropertyName<LuminaJsx.IntrinsicElements, T>];
type DragAndDropSelector = string | SelectorOptions;
type PointerPosition = {
vertical?: "bottom" | "center" | "top";
horizontal?: "left" | "center" | "right";
offset?: [number, number];
};
interface SelectorOptions {
element: string;
shadow?: string;
pointerPosition?: PointerPosition;
}
type MouseInitEvent = Pick<
MouseEvent,
"bubbles" | "cancelable" | "composed" | "screenX" | "screenY" | "clientX" | "clientY"
>;
/**
* Drag and drop utility based on https://github.com/puppeteer/puppeteer/issues/1366#issuecomment-615887204
*
* @param {E2EPage} page - the e2e page
* @param {DragAndDropSelector} dragStartSelector - Selector for the drag's start
* @param {DragAndDropSelector} dragEndSelector - Selector for the drag's end
*/
export async function dragAndDrop(
page: E2EPage,
dragStartSelector: DragAndDropSelector,
dragEndSelector: DragAndDropSelector,
): Promise<void> {
async function getBounds(selector: DragAndDropSelector): Promise<BoundingBox> {
const elementHandle =
typeof selector === "string"
? await page.waitForSelector(selector)
: await page.evaluateHandle(({ element, shadow }) => {
const target = document.querySelector(element);
return shadow ? target.shadowRoot.querySelector(shadow) : target;
}, selector);
return elementHandle.asElement().boundingBox();
}
async function createEventInitializer(selector: DragAndDropSelector): Promise<MouseInitEvent> {
const {
vertical: verticalPos,
horizontal: horizontalPos,
offset = [0, 0],
}: PointerPosition = typeof selector === "string" || !selector.pointerPosition
? { vertical: "center" }
: selector.pointerPosition;
const { height, width, x, y } = await getBounds(selector);
const verticalOffset = verticalPos === "top" ? 0 : verticalPos === "bottom" ? height : height / 2;
const horizontalOffset = horizontalPos === "left" ? 0 : horizontalPos === "right" ? width : width / 2;
const eventX = x + horizontalOffset + offset[0];
const eventY = y + verticalOffset + offset[1];
return {
bubbles: true,
cancelable: true,
composed: true,
screenX: eventX,
screenY: eventY,
clientX: eventX,
clientY: eventY,
};
}
async function browserContextFunction(
dragStartSelector: DragAndDropSelector,
dragEndSelector: DragAndDropSelector,
dragStartInitializer: MouseInitEvent,
dragEndInitializer: MouseInitEvent,
): Promise<void> {
function getElement(selector: DragAndDropSelector): Element {
if (typeof selector === "string") {
return document.querySelector(selector);
}
const element = document.querySelector(selector.element);
return selector.shadow ? element.shadowRoot.querySelector(selector.shadow) : element;
}
const dragStart = getElement(dragStartSelector);
let dragEnd = getElement(dragEndSelector);
// if has child, put at the end.
dragEnd = dragEnd.lastElementChild || dragEnd;
dragStart.dispatchEvent(new PointerEvent("pointerdown", dragStartInitializer));
dragStart.dispatchEvent(new DragEvent("dragstart", dragStartInitializer));
await new Promise((resolve) => window.setTimeout(resolve, 2000));
dragEnd.dispatchEvent(new MouseEvent("dragenter", dragEndInitializer));
dragStart.dispatchEvent(new DragEvent("dragend", dragEndInitializer));
}
return page.evaluate(
browserContextFunction,
dragStartSelector,
dragEndSelector,
await createEventInitializer(dragStartSelector),
await createEventInitializer(dragEndSelector),
);
}
/**
*
* @param {E2EElement} input - the element to select text from
* @returns {Promise<void>}
*/
export function selectText(input: E2EElement): Promise<void> {
// workaround for selecting text based on https://github.com/puppeteer/puppeteer/issues/1313#issuecomment-436932478
return input.click({ clickCount: 3 });
}
/**
* Helper to get an E2EElement's x,y coordinates.
*
* @param {E2EPage} page - the e2e page
* @param {string} elementSelector - the element selector
* @param {string} shadowSelector - the shadowRoot selector
* @deprecated Use `getElementRect` instead.
*/
export async function getElementXY(
page: E2EPage,
elementSelector: string,
shadowSelector?: string,
): Promise<[number, number]> {
return page.evaluate(
([elementSelector, shadowSelector]): [number, number] => {
const element = document.querySelector(elementSelector);
const measureTarget = shadowSelector ? element.shadowRoot.querySelector(shadowSelector) : element;
const { x, y } = measureTarget.getBoundingClientRect();
return [x, y];
},
[elementSelector, shadowSelector],
);
}
/**
* Helper to get an E2EElement's DOMRect object.
*
* @param {E2EPage} page - the e2e page
* @param {string} elementSelector - the element selector
* @param {string} shadowSelector - the shadowRoot selector
* @returns {Promise<DOMRect>} Promise with DOMRect object.
*/
export async function getElementRect(
page: E2EPage,
elementSelector: string,
shadowSelector?: string,
): Promise<DOMRect> {
return page.evaluate(
([elementSelector, shadowSelector]): DOMRect => {
const element = document.querySelector(elementSelector);
const measureTarget = shadowSelector ? element.shadowRoot.querySelector(shadowSelector) : element;
return measureTarget.getBoundingClientRect().toJSON();
},
[elementSelector, shadowSelector],
);
}
/**
* This util helps visualize mouse movement when running tests in headful mode.
* Note that this util should only be used for test debugging purposes and not be included in a test.
* Based on https://github.com/puppeteer/puppeteer/issues/4378#issuecomment-499726973
*
* @example
* import { visualizeMouseCursor } from "../../tests/utils";
*
* const page = await newE2EPage();
* await page.setContent(`<calcite-tooltip>Content</calcite-tooltip>`);
*
* await visualizeMouseCursor(page);
* await page.waitForChanges();
* @param {E2EPage} page - the e2e page
*/
export async function visualizeMouseCursor(page: E2EPage): Promise<void> {
await page.evaluate(() => {
const box = document.createElement("puppeteer-mouse-pointer");
const styleElement = document.createElement("style");
styleElement.innerHTML = `
puppeteer-mouse-pointer {
pointer-events: none;
position: absolute;
top: 0;
z-index: 10000;
left: 0;
width: 20px;
height: 20px;
background: rgba(0,0,0,.4);
border: 1px solid white;
border-radius: 10px;
margin: -10px 0 0 -10px;
padding: 0;
transition: background .2s, border-radius .2s, border-color .2s;
}
puppeteer-mouse-pointer.button-1 {
transition: none;
background: rgba(0,0,0,0.9);
}
puppeteer-mouse-pointer.button-2 {
transition: none;
border-color: rgba(0,0,255,0.9);
}
puppeteer-mouse-pointer.button-3 {
transition: none;
border-radius: 4px;
}
puppeteer-mouse-pointer.button-4 {
transition: none;
border-color: rgba(255,0,0,0.9);
}
puppeteer-mouse-pointer.button-5 {
transition: none;
border-color: rgba(0,255,0,0.9);
}
`;
document.head.appendChild(styleElement);
document.body.appendChild(box);
document.addEventListener(
"mousemove",
(event) => {
box.style.left = event.pageX + "px";
box.style.top = event.pageY + "px";
updateButtons(event.buttons);
},
true,
);
document.addEventListener(
"mousedown",
(event) => {
updateButtons(event.buttons);
box.classList.add("button-" + event.which);
},
true,
);
document.addEventListener(
"mouseup",
(event) => {
updateButtons(event.buttons);
box.classList.remove("button-" + event.which);
},
true,
);
function updateButtons(buttons: number): void {
for (let i = 0; i < 5; i++) {
box.classList.toggle("button-" + i, (buttons & (1 << i)) as unknown as boolean);
}
}
});
}
/**
* Tells the browser that you wish to perform an animation.
* https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
*
* @returns {Promise<void>}
*/
export async function waitForAnimationFrame(): Promise<void> {
return new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
}
/**
* Creates an E2E page for tests that need to create and set up elements programmatically.
*
* @returns {Promise<E2EPage>} an e2e page
*/
export async function newProgrammaticE2EPage(): Promise<E2EPage> {
const page = await newE2EPage();
await page.setContent("");
return page;
}
/**
* Sets CSS vars to skip animations/transitions.
*
* @example
* import { skipAnimations } from "../../tests/utils";
*
* const page = await newE2EPage();
* await page.setContent(`<calcite-tooltip>Content</calcite-tooltip>`);
*
* await skipAnimations(page);
* await page.waitForChanges();
* @param page
*/
export async function skipAnimations(page: E2EPage): Promise<void> {
await page.addStyleTag({
content: `:root { --calcite-duration-factor: 0; }`,
});
}
interface MatchesFocusedElementOptions {
/** Set this to true when the focused element is expected to reside in the shadow DOM */
shadowed: boolean;
}
/**
* This util helps determine if a selector matches the currently focused element.
*
* @param page – the E2E page
* @param selector – selector of element to match
* @param options - options to customize the utility behavior
*/
export async function isElementFocused(
page: E2EPage,
selector: string,
options?: MatchesFocusedElementOptions,
): Promise<boolean> {
const shadowed = options?.shadowed;
return page.evaluate(
(selector: string, shadowed: boolean): boolean => {
const targetDoc = shadowed ? document.activeElement?.shadowRoot : document;
return !!targetDoc?.activeElement?.matches(selector);
},
selector,
shadowed,
);
}
type GetFocusedElementProp = {
/** Set to true to use the shadow root's active element instead of the light DOM's. */
shadow: boolean;
};
/**
* This helps get serializable properties from the focused element.
*
* @param {E2EPage} page - the E2E test page
* @param {string} prop - the property to get from the focused element (note: must be serializable)
* @param {GetFocusedElementProp} options – additional configuration options
*/
export async function getFocusedElementProp(
page: E2EPage,
prop: keyof HTMLElement,
options?: GetFocusedElementProp,
): Promise<ReturnType<E2EPage["evaluate"]>> {
return await page.evaluate(
(by: string, shadow: boolean) => {
const { activeElement } = document;
const target = shadow ? activeElement?.shadowRoot?.activeElement : activeElement;
return target?.[by];
},
prop,
options?.shadow,
);
}
/**
* Custom integer matcher to use with object matchers.
*
* @see [Custom Asymmetric Equality Testers](https://jasmine.github.io/tutorials/custom_asymmetric_equality_testers).
*/
export function toBeInteger(): any {
return {
asymmetricMatch(abc: string): boolean {
return Number.isInteger(abc);
},
jasmineToString(): string {
return `Expected value to be an integer.`;
},
};
}
/**
* Custom number matcher to use with object matchers.
*
* @see [Custom Asymmetric Equality Testers](https://jasmine.github.io/tutorials/custom_asymmetric_equality_testers).
*/
export function toBeNumber(): any {
return {
asymmetricMatch(expected: string): boolean {
return !isNaN(parseFloat(expected)) && isFinite(Number(expected));
},
jasmineToString(): string {
return `Expected value to be an number.`;
},
};
}
type HTMLSelectableElement = HTMLElement & { selectedItems: HTMLElement[] };
interface SelectedItemsAssertionOptions {
/** IDs from items to assert selection */
expectedItemIds: string[];
}
type SelectionEventTestWindow = GlobalTestProps<{ eventDetail: Selection }>;
interface SelectedItemsAsserter {
(expectedItemIds: SelectedItemsAssertionOptions["expectedItemIds"]): Promise<void>;
}
/**
* Creates a selected items asserter for a selectable component.
*
* @example
*
* const page = await newE2EPage();
* await page.setContent(
* html`<calcite-dropdown open>
* <calcite-button id="trigger" slot="trigger">Open dropdown</calcite-button>
* <calcite-dropdown-group id="group-1" selection-mode="single">
* <calcite-dropdown-item id="item-1"> Dropdown Item Content </calcite-dropdown-item>
* <calcite-dropdown-item id="item-2" selected> Dropdown Item Content </calcite-dropdown-item>
* <calcite-dropdown-item id="item-3"> Dropdown Item Content </calcite-dropdown-item>
* </calcite-dropdown-group>
* </calcite-dropdown>`,
* );
*
* const assertSelectedItems = await createSelectedItemsAsserter(page, "calcite-dropdown", "calciteDropdownSelect");
* await page.click("#item-2");
* await assertSelectedItems({ expectedItemIds: ["item-2"] });
* @param page - the e2e page
* @param selectableComponentTagName - the tag name of the selectable group element
* @param selectionEventName - the name of the selection event
*/
export async function createSelectedItemsAsserter(
page: E2EPage,
selectableComponentTagName: ComponentTag,
selectionEventName: string,
): Promise<SelectedItemsAsserter> {
await page.evaluate((eventName) => {
document.addEventListener(
eventName as any,
({ detail }: CustomEvent<Selection>) => ((window as SelectionEventTestWindow).eventDetail = detail),
);
}, selectionEventName);
return async (expectedItemIds: SelectedItemsAssertionOptions["expectedItemIds"]) => {
await page.waitForChanges();
const selectedItemIds = await page.evaluate(
(groupElementTagName) =>
document.querySelector<HTMLSelectableElement>(groupElementTagName).selectedItems.map((item) => item.id),
selectableComponentTagName,
);
expect(selectedItemIds).toHaveLength(expectedItemIds.length);
expectedItemIds.forEach((itemId, index) => expect(selectedItemIds[index]).toEqual(itemId));
};
}
/**
* Asserts the caret position of an input or textarea element.
*
* @param options - test options
* @param options.page - the e2e page
* @param options.componentTag - the component tag
* @param options.shadowInputTypeSelector - the shadow input type selector
* @param options.position - the expected caret position
* @returns {Promise<void>}
*/
export async function assertCaretPosition({
page,
componentTag,
shadowInputTypeSelector = "input",
position,
}: {
page: E2EPage;
componentTag: string;
shadowInputTypeSelector?: "textarea" | "input";
position?: number;
}): Promise<void> {
expect(
await page.evaluate(
(position, componentTag, shadowInputTypeSelector) => {
const element = document.querySelector(componentTag);
const el = element.shadowRoot.querySelector(shadowInputTypeSelector);
return el.selectionStart === (position !== undefined ? position : el.value.length);
},
position,
componentTag,
shadowInputTypeSelector,
),
).toBeTruthy();
}
/**
* This utils helps to get the element handle from an E2EElement.
*
* @param element - the E2E element
* @returns {Promise<ElementHandle>} - the element handle
*/
export async function toElementHandle(element: E2EElement): Promise<ElementHandle> {
return element.handle;
}