setup.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 {webcrypto} from 'node:crypto';
  6. import {TextDecoder, TextEncoder} from 'node:util';
  7. import {ConfigFixture} from 'sentry-fixture/config';
  8. import {resetMockDate} from 'sentry-test/utils';
  9. // eslint-disable-next-line jest/no-mocks-import
  10. import type {Client} from 'sentry/__mocks__/api';
  11. import {DEFAULT_LOCALE_DATA, setLocale} from 'sentry/locale';
  12. import ConfigStore from 'sentry/stores/configStore';
  13. import * as performanceForSentry from 'sentry/utils/performanceForSentry';
  14. /**
  15. * Set locale to English
  16. */
  17. setLocale(DEFAULT_LOCALE_DATA);
  18. /**
  19. * XXX(epurkhiser): Gross hack to fix a bug in jsdom which makes testing of
  20. * framer-motion SVG components fail
  21. *
  22. * See https://github.com/jsdom/jsdom/issues/1330
  23. */
  24. // @ts-expect-error
  25. SVGElement.prototype.getTotalLength ??= () => 1;
  26. /**
  27. * React Testing Library configuration to override the default test id attribute
  28. *
  29. * See: https://testing-library.com/docs/queries/bytestid/#overriding-data-testid
  30. */
  31. configureRtl({testIdAttribute: 'data-test-id'});
  32. /**
  33. * Mock (current) date to always be National Pasta Day
  34. * 2017-10-17T02:41:20.000Z
  35. */
  36. resetMockDate();
  37. /**
  38. * Global testing configuration
  39. */
  40. /**
  41. * Mocks
  42. */
  43. jest.mock('lodash/debounce', () =>
  44. jest.fn(fn => {
  45. fn.cancel = jest.fn();
  46. return fn;
  47. })
  48. );
  49. jest.mock('sentry/utils/recreateRoute');
  50. jest.mock('sentry/api');
  51. jest
  52. .spyOn(performanceForSentry, 'VisuallyCompleteWithData')
  53. .mockImplementation(props => props.children as ReactElement);
  54. jest.mock('scroll-to-element', () => jest.fn());
  55. jest.mock('react-router', function reactRouterMockFactory() {
  56. const ReactRouter = jest.requireActual('react-router');
  57. return {
  58. ...ReactRouter,
  59. browserHistory: {
  60. goBack: jest.fn(),
  61. push: jest.fn(),
  62. replace: jest.fn(),
  63. listen: jest.fn(() => {}),
  64. listenBefore: jest.fn(),
  65. getCurrentLocation: jest.fn(() => ({pathname: '', query: {}})),
  66. },
  67. };
  68. });
  69. jest.mock('sentry/utils/search/searchBoxTextArea');
  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. reactRouterV3BrowserTracingIntegration: 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. // Mock the crypto.subtle API for Gravatar
  197. Object.defineProperty(global.self, 'crypto', {
  198. value: {
  199. subtle: webcrypto.subtle,
  200. },
  201. });