utils.tsx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import MockDate from 'mockdate';
  2. // Taken from https://stackoverflow.com/a/56859650/1015027
  3. function findTextWithMarkup(contentNode: null | Element, textMatch: string | RegExp) {
  4. const hasText = (node: Element): boolean => {
  5. if (node.textContent === null) {
  6. return false;
  7. }
  8. if (typeof textMatch === 'string') {
  9. return node.textContent.includes(textMatch);
  10. }
  11. return textMatch.test(node.textContent);
  12. };
  13. const nodeHasText = hasText(contentNode as Element);
  14. const childrenDontHaveText = Array.from(contentNode?.children || []).every(
  15. child => !hasText(child)
  16. );
  17. return nodeHasText && childrenDontHaveText;
  18. }
  19. /**
  20. * May be used with a *ByText RTL matcher to match text within multiple nodes
  21. *
  22. * e.g.: <div>Hello <span>world</span></div>
  23. */
  24. export function textWithMarkupMatcher(textMatch: string | RegExp) {
  25. return function (_: string, element: Element | null) {
  26. return findTextWithMarkup(element, textMatch);
  27. };
  28. }
  29. export function setMockDate(date: Date | number) {
  30. MockDate.set(date);
  31. }
  32. /**
  33. * Mock (current) date to always be National Pasta Day
  34. * 2017-10-17T02:41:20.000Z
  35. */
  36. export function resetMockDate() {
  37. const constantDate = new Date(1508208080000);
  38. MockDate.set(constantDate);
  39. }