setup.ts 7.4 KB

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