with-markup.ts 996 B

123456789101112131415161718192021222324252627282930
  1. import { MatcherFunction } from '@testing-library/react'
  2. type Query = (f: MatcherFunction) => Element | Promise<Element>
  3. /*
  4. Utility function to run testing-library queries over nodes that contain html tags, as in
  5. `<p>this includes some <strong>bold</strong> text</p>`.
  6. Usage:
  7. const getByTextWithMarkup = withMarkup(screen.getByText)
  8. getByTextWithMarkup('this includes some bold text')
  9. const findByTextWithMarkup = withMarkup(screen.findByText)
  10. await findByTextWithMarkup('this includes some bold text')
  11. */
  12. const withMarkup =
  13. (query: Query) =>
  14. (text: string): Element | Promise<Element> =>
  15. query((content: string, node: Element | null) => {
  16. if (!node) {
  17. return false
  18. }
  19. const hasText = (node: Element) => node.textContent === text
  20. const childrenDontHaveText = Array.from(node.children).every(
  21. child => !hasText(child as HTMLElement)
  22. )
  23. return hasText(node) && childrenDontHaveText
  24. })
  25. export default withMarkup