setup.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /* eslint-env node */
  2. import type {ReactElement} from 'react';
  3. import {configure as configureRtl} from '@testing-library/react'; // eslint-disable-line no-restricted-imports
  4. import MockDate from 'mockdate';
  5. import {TextDecoder, TextEncoder} from 'node:util';
  6. import {ConfigFixture} from 'sentry-fixture/config';
  7. // eslint-disable-next-line jest/no-mocks-import
  8. import type {Client} from 'sentry/__mocks__/api';
  9. import ConfigStore from 'sentry/stores/configStore';
  10. import * as performanceForSentry from 'sentry/utils/performanceForSentry';
  11. /**
  12. * XXX(epurkhiser): Gross hack to fix a bug in jsdom which makes testing of
  13. * framer-motion SVG components fail
  14. *
  15. * See https://github.com/jsdom/jsdom/issues/1330
  16. */
  17. // @ts-expect-error
  18. SVGElement.prototype.getTotalLength ??= () => 1;
  19. /**
  20. * React Testing Library configuration to override the default test id attribute
  21. *
  22. * See: https://testing-library.com/docs/queries/bytestid/#overriding-data-testid
  23. */
  24. configureRtl({testIdAttribute: 'data-test-id'});
  25. /**
  26. * Mock (current) date to always be National Pasta Day
  27. * 2017-10-17T02:41:20.000Z
  28. */
  29. const constantDate = new Date(1508208080000);
  30. MockDate.set(constantDate);
  31. /**
  32. * Global testing configuration
  33. */
  34. /**
  35. * Mocks
  36. */
  37. jest.mock('lodash/debounce', () =>
  38. jest.fn(fn => {
  39. fn.cancel = jest.fn();
  40. return fn;
  41. })
  42. );
  43. jest.mock('sentry/utils/recreateRoute');
  44. jest.mock('sentry/api');
  45. jest
  46. .spyOn(performanceForSentry, 'VisuallyCompleteWithData')
  47. .mockImplementation(props => props.children as ReactElement);
  48. jest.mock('scroll-to-element', () => jest.fn());
  49. jest.mock('react-router', function reactRouterMockFactory() {
  50. const ReactRouter = jest.requireActual('react-router');
  51. return {
  52. ...ReactRouter,
  53. browserHistory: {
  54. goBack: jest.fn(),
  55. push: jest.fn(),
  56. replace: jest.fn(),
  57. listen: jest.fn(() => {}),
  58. listenBefore: jest.fn(),
  59. getCurrentLocation: jest.fn(() => ({pathname: '', query: {}})),
  60. },
  61. };
  62. });
  63. jest.mock('sentry/utils/search/searchBoxTextArea');
  64. jest.mock('react-virtualized', function reactVirtualizedMockFactory() {
  65. const ActualReactVirtualized = jest.requireActual('react-virtualized');
  66. return {
  67. ...ActualReactVirtualized,
  68. AutoSizer: ({children}) => children({width: 100, height: 100}),
  69. };
  70. });
  71. jest.mock('echarts-for-react/lib/core', function echartsMockFactory() {
  72. // We need to do this because `jest.mock` gets hoisted by babel and `React` is not
  73. // guaranteed to be in scope
  74. const ReactActual = require('react');
  75. // We need a class component here because `BaseChart` passes `ref` which will
  76. // error if we return a stateless/functional component
  77. return class extends ReactActual.Component {
  78. render() {
  79. return null;
  80. }
  81. };
  82. });
  83. jest.mock('@sentry/react', function sentryReact() {
  84. const SentryReact = jest.requireActual('@sentry/react');
  85. return {
  86. init: jest.fn(),
  87. configureScope: jest.fn(),
  88. setTag: jest.fn(),
  89. setTags: jest.fn(),
  90. setExtra: jest.fn(),
  91. setExtras: jest.fn(),
  92. captureBreadcrumb: jest.fn(),
  93. addBreadcrumb: jest.fn(),
  94. captureMessage: jest.fn(),
  95. captureException: jest.fn(),
  96. showReportDialog: jest.fn(),
  97. startSpan: jest.spyOn(SentryReact, 'startSpan'),
  98. finishSpan: jest.fn(),
  99. lastEventId: jest.fn(),
  100. getClient: jest.spyOn(SentryReact, 'getClient'),
  101. getCurrentHub: jest.spyOn(SentryReact, 'getCurrentHub'),
  102. withScope: jest.spyOn(SentryReact, 'withScope'),
  103. Hub: SentryReact.Hub,
  104. Scope: SentryReact.Scope,
  105. Severity: SentryReact.Severity,
  106. withProfiler: SentryReact.withProfiler,
  107. metrics: {
  108. MetricsAggregator: jest.fn().mockReturnValue({}),
  109. metricsAggregatorIntegration: jest.fn(),
  110. increment: jest.fn(),
  111. gauge: jest.fn(),
  112. set: jest.fn(),
  113. distribution: jest.fn(),
  114. },
  115. BrowserTracing: jest.fn().mockReturnValue({}),
  116. reactRouterV3BrowserTracingIntegration: jest.fn().mockReturnValue({}),
  117. BrowserProfilingIntegration: jest.fn().mockReturnValue({}),
  118. addGlobalEventProcessor: jest.fn(),
  119. BrowserClient: jest.fn().mockReturnValue({
  120. captureEvent: jest.fn(),
  121. }),
  122. startTransaction: () => ({
  123. finish: jest.fn(),
  124. setTag: jest.fn(),
  125. setData: jest.fn(),
  126. setStatus: jest.fn(),
  127. startChild: jest.fn().mockReturnValue({
  128. finish: jest.fn(),
  129. }),
  130. }),
  131. };
  132. });
  133. ConfigStore.loadInitialData(ConfigFixture());
  134. /**
  135. * Test Globals
  136. */
  137. declare global {
  138. /**
  139. * Generates a promise that resolves on the next macro-task
  140. */
  141. // biome-ignore lint/style/noVar: Not required
  142. var tick: () => Promise<void>;
  143. /**
  144. * Used to mock API requests
  145. */
  146. // biome-ignore lint/style/noVar: Not required
  147. var MockApiClient: typeof Client;
  148. }
  149. // needed by cbor-web for webauthn
  150. window.TextEncoder = TextEncoder;
  151. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  152. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  153. window.tick = () => new Promise(resolve => setTimeout(resolve));
  154. window.MockApiClient = jest.requireMock('sentry/api').Client;
  155. window.scrollTo = jest.fn();
  156. // We need to re-define `window.location`, otherwise we can't spyOn certain
  157. // methods as `window.location` is read-only
  158. Object.defineProperty(window, 'location', {
  159. value: {...window.location, assign: jest.fn(), reload: jest.fn(), replace: jest.fn()},
  160. configurable: true,
  161. writable: true,
  162. });
  163. // The JSDOM implementation is too slow
  164. // Especially for dropdowns that try to position themselves
  165. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  166. Object.defineProperty(window, 'getComputedStyle', {
  167. value: (el: HTMLElement) => {
  168. /**
  169. * This is based on the jsdom implementation of getComputedStyle
  170. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  171. *
  172. * It is missing global style parsing and will only return styles applied directly to an element.
  173. * Will not return styles that are global or from emotion
  174. */
  175. const declaration = new CSSStyleDeclaration();
  176. const {style} = el;
  177. Array.prototype.forEach.call(style, (property: string) => {
  178. declaration.setProperty(
  179. property,
  180. style.getPropertyValue(property),
  181. style.getPropertyPriority(property)
  182. );
  183. });
  184. return declaration;
  185. },
  186. configurable: true,
  187. writable: true,
  188. });
  189. window.IntersectionObserver = class IntersectionObserver {
  190. root = null;
  191. rootMargin = '';
  192. thresholds = [];
  193. takeRecords = jest.fn();
  194. constructor() {}
  195. observe() {}
  196. unobserve() {}
  197. disconnect() {}
  198. };