Skip to content

Instantly share code, notes, and snippets.

@itsravenous
Created July 21, 2022 10:48
Show Gist options
  • Save itsravenous/cedd15d28298fb2b898bed055e6d13b6 to your computer and use it in GitHub Desktop.
Save itsravenous/cedd15d28298fb2b898bed055e6d13b6 to your computer and use it in GitHub Desktop.
Custom matcher for testing-library/* to find text broken up by elements
/**
* A TextMatch (see https://testing-library.com/docs/queries/about#textmatch)
* which will match a text string broken across multiple elements.
* Useful for finding, e.g. "hello there" in <p>hello <b>there</b></p>
*/
export const matchTextAcrossElements =
(text: string) => (content: string, element: Element | null) => {
const hasText = (element) => element.textContent === text;
const elementHasText = hasText(element);
const childrenDontHaveText = Array.from(element?.children || []).every(
(child) => !hasText(child)
);
return elementHasText && childrenDontHaveText;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment