setup.ts 7.4 KB

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