setup.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. jest.mock('getsentry/utils/stripe');
  59. jest.mock('getsentry/utils/trackMarketingEvent');
  60. jest.mock('getsentry/utils/trackAmplitudeEvent');
  61. jest.mock('getsentry/utils/trackReloadEvent');
  62. jest.mock('getsentry/utils/trackMetric');
  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: ({
  76. children,
  77. }: {
  78. children: (props: {height: number; width: number}) => React.ReactNode;
  79. }) => children({width: 100, height: 100}),
  80. };
  81. });
  82. jest.mock('echarts-for-react/lib/core', function echartsMockFactory() {
  83. // We need to do this because `jest.mock` gets hoisted by babel and `React` is not
  84. // guaranteed to be in scope
  85. const ReactActual = require('react');
  86. // We need a class component here because `BaseChart` passes `ref` which will
  87. // error if we return a stateless/functional component
  88. return class extends ReactActual.Component {
  89. render() {
  90. return null;
  91. }
  92. };
  93. });
  94. jest.mock('@sentry/react', function sentryReact() {
  95. const SentryReact = jest.requireActual('@sentry/react');
  96. return {
  97. ...SentryReact,
  98. init: jest.fn(),
  99. setTag: jest.fn(),
  100. setTags: jest.fn(),
  101. setExtra: jest.fn(),
  102. setExtras: jest.fn(),
  103. captureBreadcrumb: jest.fn(),
  104. addBreadcrumb: jest.fn(),
  105. captureMessage: jest.fn(),
  106. captureException: jest.fn(),
  107. showReportDialog: jest.fn(),
  108. getDefaultIntegrations: jest.spyOn(SentryReact, 'getDefaultIntegrations'),
  109. startSpan: jest.spyOn(SentryReact, 'startSpan'),
  110. finishSpan: jest.fn(),
  111. lastEventId: jest.fn(),
  112. getClient: jest.spyOn(SentryReact, 'getClient'),
  113. getCurrentScope: jest.spyOn(SentryReact, 'getCurrentScope'),
  114. withScope: jest.spyOn(SentryReact, 'withScope'),
  115. withProfiler: SentryReact.withProfiler,
  116. metrics: {
  117. increment: jest.fn(),
  118. gauge: jest.fn(),
  119. set: jest.fn(),
  120. distribution: jest.fn(),
  121. },
  122. reactRouterV6BrowserTracingIntegration: jest.fn().mockReturnValue({}),
  123. browserTracingIntegration: jest.fn().mockReturnValue({}),
  124. browserProfilingIntegration: jest.fn().mockReturnValue({}),
  125. addEventProcessor: jest.fn(),
  126. BrowserClient: jest.fn().mockReturnValue({
  127. captureEvent: jest.fn(),
  128. }),
  129. startInactiveSpan: () => ({
  130. end: jest.fn(),
  131. setStatus: jest.fn(),
  132. startChild: jest.fn().mockReturnValue({
  133. end: jest.fn(),
  134. }),
  135. }),
  136. };
  137. });
  138. ConfigStore.loadInitialData(ConfigFixture());
  139. /**
  140. * Test Globals
  141. */
  142. declare global {
  143. /**
  144. * Generates a promise that resolves on the next macro-task
  145. */
  146. // eslint-disable-next-line no-var
  147. var tick: () => Promise<void>;
  148. /**
  149. * Used to mock API requests
  150. */
  151. // eslint-disable-next-line no-var
  152. var MockApiClient: typeof Client;
  153. }
  154. // needed by cbor-web for webauthn
  155. window.TextEncoder = TextEncoder;
  156. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  157. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  158. window.tick = () => new Promise(resolve => setTimeout(resolve));
  159. window.MockApiClient = jest.requireMock('sentry/api').Client;
  160. window.scrollTo = jest.fn();
  161. window.ra = {event: jest.fn()};
  162. // We need to re-define `window.location`, otherwise we can't spyOn certain
  163. // methods as `window.location` is read-only
  164. Object.defineProperty(window, 'location', {
  165. value: {...window.location, assign: jest.fn(), reload: jest.fn(), replace: jest.fn()},
  166. configurable: true,
  167. writable: true,
  168. });
  169. // The JSDOM implementation is too slow
  170. // Especially for dropdowns that try to position themselves
  171. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  172. Object.defineProperty(window, 'getComputedStyle', {
  173. value: (el: HTMLElement) => {
  174. /**
  175. * This is based on the jsdom implementation of getComputedStyle
  176. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  177. *
  178. * It is missing global style parsing and will only return styles applied directly to an element.
  179. * Will not return styles that are global or from emotion
  180. */
  181. const declaration = new CSSStyleDeclaration();
  182. const {style} = el;
  183. Array.prototype.forEach.call(style, (property: string) => {
  184. declaration.setProperty(
  185. property,
  186. style.getPropertyValue(property),
  187. style.getPropertyPriority(property)
  188. );
  189. });
  190. return declaration;
  191. },
  192. configurable: true,
  193. writable: true,
  194. });
  195. window.IntersectionObserver = class IntersectionObserver {
  196. root = null;
  197. rootMargin = '';
  198. thresholds = [];
  199. takeRecords = jest.fn();
  200. observe() {}
  201. unobserve() {}
  202. disconnect() {}
  203. };
  204. window.ResizeObserver = class ResizeObserver {
  205. observe() {}
  206. unobserve() {}
  207. disconnect() {}
  208. };
  209. // Mock the crypto.subtle API for Gravatar
  210. Object.defineProperty(global.self, 'crypto', {
  211. value: {
  212. subtle: webcrypto.subtle,
  213. },
  214. });
  215. // Using `:focus-visible` in `querySelector` or `matches` will throw an error in JSDOM.
  216. // See https://github.com/jsdom/jsdom/issues/3055
  217. // eslint-disable-next-line testing-library/no-node-access
  218. const originalQuerySelector = HTMLElement.prototype.querySelector;
  219. const originalMatches = HTMLElement.prototype.matches;
  220. // eslint-disable-next-line testing-library/no-node-access
  221. HTMLElement.prototype.querySelector = function (selectors: string) {
  222. if (selectors === ':focus-visible') {
  223. return null;
  224. }
  225. return originalQuerySelector.call(this, selectors);
  226. };
  227. HTMLElement.prototype.matches = function (selectors: string) {
  228. if (selectors === ':focus-visible') {
  229. return false;
  230. }
  231. return originalMatches.call(this, selectors);
  232. };