setup.ts 6.7 KB

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