Skip to content

Commit

Permalink
test: Add support for querying shadow DOM
Browse files Browse the repository at this point in the history
Add a `querySelectorAll()` variant which can transparently pierce and
traverse shadow DOMs without having to know their structure (i.e. doing
selectors piece-wise and iterating on their `.shadowRoot` attribute).

This makes it a lot more convenient to write tests for pages which use
web components, like https://patternflyelements.org.
  • Loading branch information
martinpitt committed Nov 12, 2024
1 parent 9601aee commit f11e9e8
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions test/common/test-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,30 @@
* These are routines used by our testing code.
*/

// Like querySelectorAll(), but traverses shadow DOM
window.querySelectorAllDeep = function(query, element) {
const result = Array.from(
element.shadowRoot
? element.shadowRoot.childNodes
: element.nodeName === 'SLOT' ? element.assignedElements() : element.childNodes,
)
.filter(element => element instanceof Element)
.map(element => window.querySelectorAllDeep(query, element))
.flat();

if (element.matches?.(query))
result.push(element);
return result;
};

window.ph_select = function(sel) {
if (sel.includes(":contains(")) {
if (!window.Sizzle) {
throw new Error("Using ':contains' when window.Sizzle is not available.");
}
return window.Sizzle(sel);
} else {
return Array.from(document.querySelectorAll(sel));
}
} else
return window.querySelectorAllDeep(sel, document);
};

window.ph_only = function(els, sel) {
Expand Down

0 comments on commit f11e9e8

Please sign in to comment.