setup.ts 6.7 KB

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