setup.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. 'use strict';
  2. import '@testing-library/jest-dom';
  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. // @ts-expect-error XXX(epurkhiser): Gross hack to fix a bug in jsdom which makes testing of
  26. // framer-motion SVG components fail
  27. // See https://github.com/jsdom/jsdom/issues/1330
  28. SVGElement.prototype.getTotalLength ??= () => 1;
  29. /**
  30. * React Testing Library configuration to override the default test id attribute
  31. *
  32. * See: https://testing-library.com/docs/queries/bytestid/#overriding-data-testid
  33. */
  34. configureRtl({testIdAttribute: 'data-test-id'});
  35. /**
  36. * Mock (current) date to always be National Pasta Day
  37. * 2017-10-17T02:41:20.000Z
  38. */
  39. resetMockDate();
  40. /**
  41. * Global testing configuration
  42. */
  43. /**
  44. * Mocks
  45. */
  46. jest.mock('lodash/debounce', () =>
  47. jest.fn(fn => {
  48. fn.cancel = jest.fn();
  49. return fn;
  50. })
  51. );
  52. jest.mock('sentry/utils/recreateRoute');
  53. jest.mock('sentry/api');
  54. jest
  55. .spyOn(performanceForSentry, 'VisuallyCompleteWithData')
  56. .mockImplementation(props => props.children as ReactElement);
  57. jest.mock('scroll-to-element', () => jest.fn());
  58. DANGEROUS_SET_TEST_HISTORY({
  59. goBack: jest.fn(),
  60. push: jest.fn(),
  61. replace: jest.fn(),
  62. listen: jest.fn(() => {}),
  63. listenBefore: jest.fn(),
  64. getCurrentLocation: jest.fn(() => ({pathname: '', query: {}})),
  65. });
  66. jest.mock('react-virtualized', function reactVirtualizedMockFactory() {
  67. const ActualReactVirtualized = jest.requireActual('react-virtualized');
  68. return {
  69. ...ActualReactVirtualized,
  70. AutoSizer: ({
  71. children,
  72. }: {
  73. children: (props: {height: number; width: number}) => React.ReactNode;
  74. }) => 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. // eslint-disable-next-line no-var
  142. var tick: () => Promise<void>;
  143. /**
  144. * Used to mock API requests
  145. */
  146. // eslint-disable-next-line no-var
  147. var MockApiClient: typeof Client;
  148. }
  149. // needed by cbor-web for webauthn
  150. window.TextEncoder = TextEncoder;
  151. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  152. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  153. window.tick = () => new Promise(resolve => setTimeout(resolve));
  154. window.MockApiClient = jest.requireMock('sentry/api').Client;
  155. window.scrollTo = jest.fn();
  156. // We need to re-define `window.location`, otherwise we can't spyOn certain
  157. // methods as `window.location` is read-only
  158. Object.defineProperty(window, 'location', {
  159. value: {...window.location, assign: jest.fn(), reload: jest.fn(), replace: jest.fn()},
  160. configurable: true,
  161. writable: true,
  162. });
  163. // The JSDOM implementation is too slow
  164. // Especially for dropdowns that try to position themselves
  165. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  166. Object.defineProperty(window, 'getComputedStyle', {
  167. value: (el: HTMLElement) => {
  168. /**
  169. * This is based on the jsdom implementation of getComputedStyle
  170. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  171. *
  172. * It is missing global style parsing and will only return styles applied directly to an element.
  173. * Will not return styles that are global or from emotion
  174. */
  175. const declaration = new CSSStyleDeclaration();
  176. const {style} = el;
  177. Array.prototype.forEach.call(style, (property: string) => {
  178. declaration.setProperty(
  179. property,
  180. style.getPropertyValue(property),
  181. style.getPropertyPriority(property)
  182. );
  183. });
  184. return declaration;
  185. },
  186. configurable: true,
  187. writable: true,
  188. });
  189. window.IntersectionObserver = class IntersectionObserver {
  190. root = null;
  191. rootMargin = '';
  192. thresholds = [];
  193. takeRecords = jest.fn();
  194. observe() {}
  195. unobserve() {}
  196. disconnect() {}
  197. };
  198. window.ResizeObserver = class ResizeObserver {
  199. observe() {}
  200. unobserve() {}
  201. disconnect() {}
  202. };
  203. // Mock the crypto.subtle API for Gravatar
  204. Object.defineProperty(global.self, 'crypto', {
  205. value: {
  206. subtle: webcrypto.subtle,
  207. },
  208. });