setup.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 {TextDecoder, TextEncoder} from 'node:util';
  5. import {ConfigFixture} from 'sentry-fixture/config';
  6. import {resetMockDate} from 'sentry-test/utils';
  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. resetMockDate();
  30. /**
  31. * Global testing configuration
  32. */
  33. /**
  34. * Mocks
  35. */
  36. jest.mock('lodash/debounce', () =>
  37. jest.fn(fn => {
  38. fn.cancel = jest.fn();
  39. return fn;
  40. })
  41. );
  42. jest.mock('sentry/utils/recreateRoute');
  43. jest.mock('sentry/api');
  44. jest
  45. .spyOn(performanceForSentry, 'VisuallyCompleteWithData')
  46. .mockImplementation(props => props.children as ReactElement);
  47. jest.mock('scroll-to-element', () => jest.fn());
  48. jest.mock('react-router', function reactRouterMockFactory() {
  49. const ReactRouter = jest.requireActual('react-router');
  50. return {
  51. ...ReactRouter,
  52. browserHistory: {
  53. goBack: jest.fn(),
  54. push: jest.fn(),
  55. replace: jest.fn(),
  56. listen: jest.fn(() => {}),
  57. listenBefore: jest.fn(),
  58. getCurrentLocation: jest.fn(() => ({pathname: '', query: {}})),
  59. },
  60. };
  61. });
  62. jest.mock('sentry/utils/search/searchBoxTextArea');
  63. jest.mock('react-virtualized', function reactVirtualizedMockFactory() {
  64. const ActualReactVirtualized = jest.requireActual('react-virtualized');
  65. return {
  66. ...ActualReactVirtualized,
  67. AutoSizer: ({children}) => children({width: 100, height: 100}),
  68. };
  69. });
  70. jest.mock('echarts-for-react/lib/core', function echartsMockFactory() {
  71. // We need to do this because `jest.mock` gets hoisted by babel and `React` is not
  72. // guaranteed to be in scope
  73. const ReactActual = require('react');
  74. // We need a class component here because `BaseChart` passes `ref` which will
  75. // error if we return a stateless/functional component
  76. return class extends ReactActual.Component {
  77. render() {
  78. return null;
  79. }
  80. };
  81. });
  82. jest.mock('@sentry/react', function sentryReact() {
  83. const SentryReact = jest.requireActual('@sentry/react');
  84. return {
  85. init: jest.fn(),
  86. configureScope: jest.fn(), // Needed atm for getsentry - TODO: remove once we moved to v8 api in getsentry
  87. setTag: jest.fn(),
  88. setTags: jest.fn(),
  89. setExtra: jest.fn(),
  90. setExtras: jest.fn(),
  91. captureBreadcrumb: jest.fn(),
  92. addBreadcrumb: jest.fn(),
  93. captureMessage: jest.fn(),
  94. captureException: jest.fn(),
  95. showReportDialog: jest.fn(),
  96. getDefaultIntegrations: jest.spyOn(SentryReact, 'getDefaultIntegrations'),
  97. startSpan: jest.spyOn(SentryReact, 'startSpan'),
  98. finishSpan: jest.fn(),
  99. lastEventId: jest.fn(),
  100. getClient: jest.spyOn(SentryReact, 'getClient'),
  101. getActiveTransaction: jest.spyOn(SentryReact, 'getActiveTransaction'),
  102. getCurrentHub: jest.spyOn(SentryReact, 'getCurrentHub'),
  103. getCurrentScope: jest.spyOn(SentryReact, 'getCurrentScope'),
  104. withScope: jest.spyOn(SentryReact, 'withScope'),
  105. Hub: SentryReact.Hub,
  106. Scope: SentryReact.Scope,
  107. Severity: SentryReact.Severity,
  108. withProfiler: SentryReact.withProfiler,
  109. metrics: {
  110. MetricsAggregator: jest.fn().mockReturnValue({}),
  111. metricsAggregatorIntegration: jest.fn(),
  112. increment: jest.fn(),
  113. gauge: jest.fn(),
  114. set: jest.fn(),
  115. distribution: jest.fn(),
  116. },
  117. reactRouterV3BrowserTracingIntegration: jest.fn().mockReturnValue({}),
  118. browserTracingIntegration: jest.fn().mockReturnValue({}),
  119. browserProfilingIntegration: jest.fn().mockReturnValue({}),
  120. addGlobalEventProcessor: jest.fn(), // Kept atm for getsentry - TODO: remove once we moved to v8 api in getsentry
  121. addEventProcessor: jest.fn(),
  122. BrowserClient: jest.fn().mockReturnValue({
  123. captureEvent: jest.fn(),
  124. }),
  125. startTransaction: () => ({
  126. // Kept atm for getsentry - TODO: remove once we moved to v8 api in getsentry
  127. finish: jest.fn(),
  128. setTag: jest.fn(),
  129. setData: jest.fn(),
  130. setStatus: jest.fn(),
  131. startChild: jest.fn().mockReturnValue({
  132. finish: jest.fn(),
  133. }),
  134. }),
  135. startInactiveSpan: () => ({
  136. end: jest.fn(),
  137. setStatus: jest.fn(),
  138. startChild: jest.fn().mockReturnValue({
  139. end: jest.fn(),
  140. }),
  141. }),
  142. };
  143. });
  144. ConfigStore.loadInitialData(ConfigFixture());
  145. /**
  146. * Test Globals
  147. */
  148. declare global {
  149. /**
  150. * Generates a promise that resolves on the next macro-task
  151. */
  152. var tick: () => Promise<void>;
  153. /**
  154. * Used to mock API requests
  155. */
  156. var MockApiClient: typeof Client;
  157. }
  158. // needed by cbor-web for webauthn
  159. window.TextEncoder = TextEncoder;
  160. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  161. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  162. window.tick = () => new Promise(resolve => setTimeout(resolve));
  163. window.MockApiClient = jest.requireMock('sentry/api').Client;
  164. window.scrollTo = jest.fn();
  165. // We need to re-define `window.location`, otherwise we can't spyOn certain
  166. // methods as `window.location` is read-only
  167. Object.defineProperty(window, 'location', {
  168. value: {...window.location, assign: jest.fn(), reload: jest.fn(), replace: jest.fn()},
  169. configurable: true,
  170. writable: true,
  171. });
  172. // The JSDOM implementation is too slow
  173. // Especially for dropdowns that try to position themselves
  174. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  175. Object.defineProperty(window, 'getComputedStyle', {
  176. value: (el: HTMLElement) => {
  177. /**
  178. * This is based on the jsdom implementation of getComputedStyle
  179. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  180. *
  181. * It is missing global style parsing and will only return styles applied directly to an element.
  182. * Will not return styles that are global or from emotion
  183. */
  184. const declaration = new CSSStyleDeclaration();
  185. const {style} = el;
  186. Array.prototype.forEach.call(style, (property: string) => {
  187. declaration.setProperty(
  188. property,
  189. style.getPropertyValue(property),
  190. style.getPropertyPriority(property)
  191. );
  192. });
  193. return declaration;
  194. },
  195. configurable: true,
  196. writable: true,
  197. });
  198. window.IntersectionObserver = class IntersectionObserver {
  199. root = null;
  200. rootMargin = '';
  201. thresholds = [];
  202. takeRecords = jest.fn();
  203. constructor() {}
  204. observe() {}
  205. unobserve() {}
  206. disconnect() {}
  207. };