utils.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Taken from https://stackoverflow.com/a/56859650/1015027
  2. function findTextWithMarkup(contentNode: null | Element, textMatch: string | RegExp) {
  3. const hasText = (node: Element): boolean => {
  4. if (node.textContent === null) {
  5. return false;
  6. }
  7. if (typeof textMatch === 'string') {
  8. return node.textContent.includes(textMatch);
  9. }
  10. return textMatch.test(node.textContent);
  11. };
  12. const nodeHasText = hasText(contentNode as Element);
  13. const childrenDontHaveText = Array.from(contentNode?.children || []).every(
  14. child => !hasText(child)
  15. );
  16. return nodeHasText && childrenDontHaveText;
  17. }
  18. /**
  19. * May be used with a *ByText RTL matcher to match text within multiple nodes
  20. *
  21. * e.g.: <div>Hello <span>world</span></div>
  22. */
  23. export function textWithMarkupMatcher(textMatch: string | RegExp) {
  24. return function (_: string, element: Element | null) {
  25. return findTextWithMarkup(element, textMatch);
  26. };
  27. }
  28. /**
  29. * @deprecated (This function is a workaround for test files that still use
  30. * enzyme.)
  31. *
  32. * Triggers onPress events on components that use react-aria (e.g. the
  33. * dropdown menu). These components require more complex events than what
  34. * enzyme can simulate with `.simulate('click')`. Preferably, we should use
  35. * the 'user-event' library from react testing library. Read more:
  36. * https://react-spectrum.adobe.com/react-spectrum/testing.html#triggering-events
  37. */
  38. export function triggerPress(element) {
  39. element.prop('onClick')({
  40. button: 0,
  41. detail: 0,
  42. nativeEvent: {detail: 0},
  43. currentTarget: element.getDOMNode(),
  44. target: element.getDOMNode(),
  45. stopPropagation: () => {},
  46. preventDefault: () => {},
  47. });
  48. }