Skip to content

Instantly share code, notes, and snippets.

@FaberVitale
Created August 29, 2022 06:57
Show Gist options
  • Save FaberVitale/9c4c6f90a912e458947d17d57d94df0e to your computer and use it in GitHub Desktop.
Save FaberVitale/9c4c6f90a912e458947d17d57d94df0e to your computer and use it in GitHub Desktop.
Simple selector function useful in testing environments. Throws error to indicate that the test has failed
/**
* Locates a descendant of `rootElement` given selector provided
* or throws error if output element is not found
* or is not an instance of input `DomElementClass`.
*
* ### Example
*
* ```ts
* const btn = queryElement(
* renderRes.container,
* 'button[type="submit"]',
* HTMLButtonElement
* );
* ```
*
* @param rootElement
* @param selector
* @param DomElementClass
* @returns
*/
function queryElement<Elem extends Element>(
rootElement: Element,
selector: string,
DomElementClass: new () => Elem
): Elem {
const output = rootElement.querySelector(selector);
if (!(output instanceof DomElementClass)) {
throw new Error(
`queryElement ${selector} not found in root ${rootElement.tagName}`
);
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment