setup.ts 7.2 KB

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