setup.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 {TextDecoder, TextEncoder} from 'node:util';
  6. import {ConfigFixture} from 'sentry-fixture/config';
  7. import {resetMockDate} from 'sentry-test/utils';
  8. // eslint-disable-next-line jest/no-mocks-import
  9. import type {Client} from 'sentry/__mocks__/api';
  10. import ConfigStore from 'sentry/stores/configStore';
  11. import * as performanceForSentry from 'sentry/utils/performanceForSentry';
  12. /**
  13. * XXX(epurkhiser): Gross hack to fix a bug in jsdom which makes testing of
  14. * framer-motion SVG components fail
  15. *
  16. * See https://github.com/jsdom/jsdom/issues/1330
  17. */
  18. // @ts-expect-error
  19. SVGElement.prototype.getTotalLength ??= () => 1;
  20. /**
  21. * React Testing Library configuration to override the default test id attribute
  22. *
  23. * See: https://testing-library.com/docs/queries/bytestid/#overriding-data-testid
  24. */
  25. configureRtl({testIdAttribute: 'data-test-id'});
  26. /**
  27. * Mock (current) date to always be National Pasta Day
  28. * 2017-10-17T02:41:20.000Z
  29. */
  30. resetMockDate();
  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(), // Needed atm for getsentry - TODO: remove once we moved to v8 api in getsentry
  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. getDefaultIntegrations: jest.spyOn(SentryReact, 'getDefaultIntegrations'),
  98. startSpan: jest.spyOn(SentryReact, 'startSpan'),
  99. finishSpan: jest.fn(),
  100. lastEventId: jest.fn(),
  101. getClient: jest.spyOn(SentryReact, 'getClient'),
  102. getActiveTransaction: jest.spyOn(SentryReact, 'getActiveTransaction'),
  103. getCurrentHub: jest.spyOn(SentryReact, 'getCurrentHub'),
  104. getCurrentScope: jest.spyOn(SentryReact, 'getCurrentScope'),
  105. withScope: jest.spyOn(SentryReact, 'withScope'),
  106. Hub: SentryReact.Hub,
  107. Scope: SentryReact.Scope,
  108. Severity: SentryReact.Severity,
  109. withProfiler: SentryReact.withProfiler,
  110. metrics: {
  111. MetricsAggregator: jest.fn().mockReturnValue({}),
  112. metricsAggregatorIntegration: jest.fn(),
  113. increment: jest.fn(),
  114. gauge: jest.fn(),
  115. set: jest.fn(),
  116. distribution: jest.fn(),
  117. },
  118. reactRouterV3BrowserTracingIntegration: jest.fn().mockReturnValue({}),
  119. browserTracingIntegration: jest.fn().mockReturnValue({}),
  120. browserProfilingIntegration: jest.fn().mockReturnValue({}),
  121. addGlobalEventProcessor: jest.fn(), // Kept atm for getsentry - TODO: remove once we moved to v8 api in getsentry
  122. addEventProcessor: jest.fn(),
  123. BrowserClient: jest.fn().mockReturnValue({
  124. captureEvent: jest.fn(),
  125. }),
  126. startTransaction: () => ({
  127. // Kept atm for getsentry - TODO: remove once we moved to v8 api in getsentry
  128. finish: jest.fn(),
  129. setTag: jest.fn(),
  130. setData: jest.fn(),
  131. setStatus: jest.fn(),
  132. startChild: jest.fn().mockReturnValue({
  133. finish: jest.fn(),
  134. }),
  135. }),
  136. startInactiveSpan: () => ({
  137. end: jest.fn(),
  138. setStatus: jest.fn(),
  139. startChild: jest.fn().mockReturnValue({
  140. end: jest.fn(),
  141. }),
  142. }),
  143. };
  144. });
  145. ConfigStore.loadInitialData(ConfigFixture());
  146. /**
  147. * Test Globals
  148. */
  149. declare global {
  150. /**
  151. * Generates a promise that resolves on the next macro-task
  152. */
  153. var tick: () => Promise<void>;
  154. /**
  155. * Used to mock API requests
  156. */
  157. var MockApiClient: typeof Client;
  158. }
  159. // needed by cbor-web for webauthn
  160. window.TextEncoder = TextEncoder;
  161. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  162. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  163. window.tick = () => new Promise(resolve => setTimeout(resolve));
  164. window.MockApiClient = jest.requireMock('sentry/api').Client;
  165. window.scrollTo = jest.fn();
  166. // We need to re-define `window.location`, otherwise we can't spyOn certain
  167. // methods as `window.location` is read-only
  168. Object.defineProperty(window, 'location', {
  169. value: {...window.location, assign: jest.fn(), reload: jest.fn(), replace: jest.fn()},
  170. configurable: true,
  171. writable: true,
  172. });
  173. // The JSDOM implementation is too slow
  174. // Especially for dropdowns that try to position themselves
  175. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  176. Object.defineProperty(window, 'getComputedStyle', {
  177. value: (el: HTMLElement) => {
  178. /**
  179. * This is based on the jsdom implementation of getComputedStyle
  180. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  181. *
  182. * It is missing global style parsing and will only return styles applied directly to an element.
  183. * Will not return styles that are global or from emotion
  184. */
  185. const declaration = new CSSStyleDeclaration();
  186. const {style} = el;
  187. Array.prototype.forEach.call(style, (property: string) => {
  188. declaration.setProperty(
  189. property,
  190. style.getPropertyValue(property),
  191. style.getPropertyPriority(property)
  192. );
  193. });
  194. return declaration;
  195. },
  196. configurable: true,
  197. writable: true,
  198. });
  199. window.IntersectionObserver = class IntersectionObserver {
  200. root = null;
  201. rootMargin = '';
  202. thresholds = [];
  203. takeRecords = jest.fn();
  204. constructor() {}
  205. observe() {}
  206. unobserve() {}
  207. disconnect() {}
  208. };