Skip to content

Commit

Permalink
feat(tools): clickElementAtOffset test helper
Browse files Browse the repository at this point in the history
  • Loading branch information
bennypowers committed Aug 22, 2023
1 parent fbd20ff commit 57b7dba
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
4 changes: 4 additions & 0 deletions .changeset/test-click-element-at-offset.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
"@patternfly/pfe-tools": minor
---
Test: add `clickElementAtOffset` utility function for tests
2 changes: 1 addition & 1 deletion .changeset/test-tools-click-el.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
---
"@patternfly/pfe-tools": minor
---
Test: add `clickElementCenter` utility function for tests
Test: add `clickElementAtCenter` utility function for tests
33 changes: 30 additions & 3 deletions tools/pfe-tools/test/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { ReactiveElement } from 'lit';

export type Position = [x: number, y: number];

export function getElementPosition(element: Element): Position {
export function getElementCenterPosition(element: Element): Position {
const { x, y, width, height } = element.getBoundingClientRect();

return [
Expand All @@ -12,8 +12,35 @@ export function getElementPosition(element: Element): Position {
];
}

export async function clickElementCenter(element: Element): Promise<void> {
const position = getElementPosition(element);
/** @deprecated - use `getElementCenterPosition` */
export const getElementPosition = getElementCenterPosition;

/**
* Click an element at approximate center, using playwright's sendMouse command
*/
export async function clickElementAtCenter(element: Element): Promise<void> {
const position = getElementCenterPosition(element);
await sendMouse({ type: 'click', position });
}

/**
* Click an element at an offset from it's top-left corner, using playwright's sendMouse command
*/
export async function clickElementAtOffset(element: Element, relativeOffset: Position): Promise<void> {
const { x, y, right, bottom } = element.getBoundingClientRect();
const [xOffset, yOffset] = relativeOffset;
const position = [
Math.round(xOffset + (xOffset < 0 ? right : x)),
Math.round(yOffset + (yOffset < 0 ? bottom : y)),
] satisfies [number, number];
const [xCoord, yCoord] = position;
// NOTE: this may fail in RTL situations?
if (xCoord > right) {
throw new Error('X offset is outside element boundaries');
}
if (yCoord > bottom) {
throw new Error('Y offset is outside element boundaries');
}
await sendMouse({ type: 'click', position });
}

Expand Down

0 comments on commit 57b7dba

Please sign in to comment.