setup.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. BrowserTracing: jest.fn().mockReturnValue({}),
  115. BrowserProfilingIntegration: jest.fn().mockReturnValue({}),
  116. addGlobalEventProcessor: jest.fn(),
  117. BrowserClient: jest.fn().mockReturnValue({
  118. captureEvent: jest.fn(),
  119. }),
  120. startTransaction: () => ({
  121. finish: jest.fn(),
  122. setTag: jest.fn(),
  123. setData: jest.fn(),
  124. setStatus: jest.fn(),
  125. startChild: jest.fn().mockReturnValue({
  126. finish: jest.fn(),
  127. }),
  128. }),
  129. };
  130. });
  131. const routerFixtures = {
  132. router: RouterFixture,
  133. location: LocationFixture,
  134. routerProps: RouterPropsFixture,
  135. routeComponentProps: RouteComponentPropsFixture,
  136. routerContext: RouterContextFixture,
  137. };
  138. const jsFixturesDirectory = path.resolve(__dirname, '../../fixtures/js-stubs/');
  139. const fixtures = makeLazyFixtures(jsFixturesDirectory, routerFixtures);
  140. ConfigStore.loadInitialData(fixtures.Config());
  141. /**
  142. * Test Globals
  143. */
  144. declare global {
  145. /**
  146. * Test stubs are automatically loaded from the fixtures/js-stubs
  147. * directory. Use these for setting up test data.
  148. *
  149. * @deprecated Please import test stubs directly and do not use this global.
  150. */
  151. // eslint-disable-next-line no-var
  152. var TestStubs: typeof fixtures;
  153. /**
  154. * Generates a promise that resolves on the next macro-task
  155. */
  156. // eslint-disable-next-line no-var
  157. var tick: () => Promise<void>;
  158. /**
  159. * Used to mock API requests
  160. */
  161. // eslint-disable-next-line no-var
  162. var MockApiClient: typeof Client;
  163. }
  164. // needed by cbor-web for webauthn
  165. window.TextEncoder = TextEncoder;
  166. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  167. window.TestStubs = fixtures;
  168. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  169. window.tick = () => new Promise(resolve => setTimeout(resolve));
  170. window.MockApiClient = jest.requireMock('sentry/api').Client;
  171. window.scrollTo = jest.fn();
  172. // We need to re-define `window.location`, otherwise we can't spyOn certain
  173. // methods as `window.location` is read-only
  174. Object.defineProperty(window, 'location', {
  175. value: {...window.location, assign: jest.fn(), reload: jest.fn(), replace: jest.fn()},
  176. configurable: true,
  177. writable: true,
  178. });
  179. // The JSDOM implementation is too slow
  180. // Especially for dropdowns that try to position themselves
  181. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  182. Object.defineProperty(window, 'getComputedStyle', {
  183. value: (el: HTMLElement) => {
  184. /**
  185. * This is based on the jsdom implementation of getComputedStyle
  186. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  187. *
  188. * It is missing global style parsing and will only return styles applied directly to an element.
  189. * Will not return styles that are global or from emotion
  190. */
  191. const declaration = new CSSStyleDeclaration();
  192. const {style} = el;
  193. Array.prototype.forEach.call(style, (property: string) => {
  194. declaration.setProperty(
  195. property,
  196. style.getPropertyValue(property),
  197. style.getPropertyPriority(property)
  198. );
  199. });
  200. return declaration;
  201. },
  202. configurable: true,
  203. writable: true,
  204. });
  205. window.IntersectionObserver = class IntersectionObserver {
  206. root = null;
  207. rootMargin = '';
  208. thresholds = [];
  209. takeRecords = jest.fn();
  210. constructor() {}
  211. observe() {}
  212. unobserve() {}
  213. disconnect() {}
  214. };