utils.tsx 1.1 KB

1234567891011121314151617181920212223242526272829
  1. import {screen} from 'sentry-test/reactTestingLibrary';
  2. // Taken from https://stackoverflow.com/a/56859650/1015027
  3. function findTextWithMarkup(contentNode: null | Element, textMatch: string | RegExp) {
  4. const hasText = (node: Element) => node.textContent === textMatch;
  5. const nodeHasText = hasText(contentNode as Element);
  6. const childrenDontHaveText = Array.from(contentNode?.children || []).every(
  7. child => !hasText(child)
  8. );
  9. return nodeHasText && childrenDontHaveText;
  10. }
  11. /**
  12. * Search for a text broken up by multiple html elements
  13. * e.g.: <div>Hello <span>world</span></div>
  14. */
  15. export function getByTextContent(textMatch: string | RegExp) {
  16. return screen.getByText((_, contentNode) => findTextWithMarkup(contentNode, textMatch));
  17. }
  18. /**
  19. * Search for *all* texts broken up by multiple html elements
  20. * e.g.: <div><div>Hello <span>world</span></div><div>Hello <span>world</span></div></div>
  21. */
  22. export function getAllByTextContent(textMatch: string | RegExp) {
  23. return screen.getAllByText((_, contentNode) =>
  24. findTextWithMarkup(contentNode, textMatch)
  25. );
  26. }