setup.ts 6.4 KB

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