setup.ts 6.6 KB

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