Skip to content

Instantly share code, notes, and snippets.

@sompylasar
Created April 6, 2018 00:13
Show Gist options
  • Save sompylasar/dfa8d7282d4d5092ca4a54dd65d606aa to your computer and use it in GitHub Desktop.
Save sompylasar/dfa8d7282d4d5092ca4a54dd65d606aa to your computer and use it in GitHub Desktop.
Cypress custom command that finds a visible element rendered visually below the previous subject. Using it to find inputs below labels that miss accessible identifiers. https://twitter.com/sompylasar/status/982027453764792320
// `queries.matches` is this function: https://github.com/kentcdodds/testing-workshop/blob/888201516879d067adddc6b6dd3c76394f0b2bee/cypress/support/queries.js#L74-L82
Cypress.Commands.add('getVisuallyBelow', { prevSubject: 'element' }, (subject, matcher) => {
const domNode = subject.get(0);
const log = Cypress.log({
name: 'GET_VISUALLY_BELOW',
message: '' + (
String(
domNode.nodeName +
'.' + domNode.className.replace(/^\s+|\s+$/g, '').replace(/\s+/, '.')
) + ' ' +
String(matcher)
),
consoleProps() {
return {
subject: subject,
matcher: matcher,
};
},
});
const doc = domNode.ownerDocument;
const normalizedMatcher = (
typeof matcher === 'function'
? matcher
: (el) => queries.matches(el.innerText, el, matcher)
);
return cy
.window({ log: false })
.then(getCommandWaiter(doc, () => {
if (!Cypress.dom.isVisible(domNode)) { return null; }
const rect = domNode.getBoundingClientRect();
if (!rect) { return null; }
const foundEls = Array.from(doc.querySelectorAll('*'))
.filter((el) => (
Cypress.dom.isVisible(el) && normalizedMatcher(el)
))
.map((el) => {
const rectBelow = el.getBoundingClientRect();
const dist = (rectBelow.top - rect.bottom);
return { el, dist };
})
.filter(({ dist }) => (dist >= 0));
foundEls.sort((left, right) => (left.dist - right.dist));
return (foundEls[0] ? foundEls[0].el : null);
}))
.then(($el) => {
log.set({ $el }).snapshot().end();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment