setup.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 type {InjectedRouter, RouteComponentProps} from 'react-router';
  7. import {configure as configureRtl} from '@testing-library/react'; // eslint-disable-line no-restricted-imports
  8. import type {Location} from 'history';
  9. import MockDate from 'mockdate';
  10. import {object as propTypesObject} from 'prop-types';
  11. import {stringify} from 'query-string';
  12. import {Organization} from 'sentry-fixture/organization';
  13. import {Project} from 'sentry-fixture/project';
  14. // eslint-disable-next-line jest/no-mocks-import
  15. import type {Client} from 'sentry/__mocks__/api';
  16. import ConfigStore from 'sentry/stores/configStore';
  17. import * as performanceForSentry from 'sentry/utils/performanceForSentry';
  18. import {makeLazyFixtures} from './sentry-test/loadFixtures';
  19. /**
  20. * XXX(epurkhiser): Gross hack to fix a bug in jsdom which makes testing of
  21. * framer-motion SVG components fail
  22. *
  23. * See https://github.com/jsdom/jsdom/issues/1330
  24. */
  25. // @ts-expect-error
  26. SVGElement.prototype.getTotalLength ??= () => 1;
  27. /**
  28. * React Testing Library configuration to override the default test id attribute
  29. *
  30. * See: https://testing-library.com/docs/queries/bytestid/#overriding-data-testid
  31. */
  32. configureRtl({testIdAttribute: 'data-test-id'});
  33. /**
  34. * Mock (current) date to always be National Pasta Day
  35. * 2017-10-17T02:41:20.000Z
  36. */
  37. const constantDate = new Date(1508208080000);
  38. MockDate.set(constantDate);
  39. /**
  40. * Global testing configuration
  41. */
  42. /**
  43. * Mocks
  44. */
  45. jest.mock('lodash/debounce', () =>
  46. jest.fn(fn => {
  47. fn.cancel = jest.fn();
  48. return fn;
  49. })
  50. );
  51. jest.mock('sentry/utils/recreateRoute');
  52. jest.mock('sentry/api');
  53. jest.mock('sentry/utils/withOrganization');
  54. jest
  55. .spyOn(performanceForSentry, 'VisuallyCompleteWithData')
  56. .mockImplementation(props => props.children as ReactElement);
  57. jest.mock('scroll-to-element', () => jest.fn());
  58. jest.mock('react-router', function reactRouterMockFactory() {
  59. const ReactRouter = jest.requireActual('react-router');
  60. return {
  61. ...ReactRouter,
  62. browserHistory: {
  63. goBack: jest.fn(),
  64. push: jest.fn(),
  65. replace: jest.fn(),
  66. listen: jest.fn(() => {}),
  67. listenBefore: jest.fn(),
  68. getCurrentLocation: jest.fn(() => ({pathname: '', query: {}})),
  69. },
  70. };
  71. });
  72. jest.mock('sentry/utils/search/searchBoxTextArea');
  73. jest.mock('react-virtualized', function reactVirtualizedMockFactory() {
  74. const ActualReactVirtualized = jest.requireActual('react-virtualized');
  75. return {
  76. ...ActualReactVirtualized,
  77. AutoSizer: ({children}) => children({width: 100, height: 100}),
  78. };
  79. });
  80. jest.mock('echarts-for-react/lib/core', function echartsMockFactory() {
  81. // We need to do this because `jest.mock` gets hoisted by babel and `React` is not
  82. // guaranteed to be in scope
  83. const ReactActual = require('react');
  84. // We need a class component here because `BaseChart` passes `ref` which will
  85. // error if we return a stateless/functional component
  86. return class extends ReactActual.Component {
  87. render() {
  88. return null;
  89. }
  90. };
  91. });
  92. jest.mock('@sentry/react', function sentryReact() {
  93. const SentryReact = jest.requireActual('@sentry/react');
  94. return {
  95. init: jest.fn(),
  96. configureScope: jest.fn(),
  97. setTag: jest.fn(),
  98. setTags: jest.fn(),
  99. setExtra: jest.fn(),
  100. setExtras: jest.fn(),
  101. captureBreadcrumb: jest.fn(),
  102. addBreadcrumb: jest.fn(),
  103. captureMessage: jest.fn(),
  104. captureException: jest.fn(),
  105. showReportDialog: jest.fn(),
  106. startSpan: jest.fn(),
  107. finishSpan: jest.fn(),
  108. lastEventId: jest.fn(),
  109. getCurrentHub: jest.spyOn(SentryReact, 'getCurrentHub'),
  110. withScope: jest.spyOn(SentryReact, 'withScope'),
  111. Hub: SentryReact.Hub,
  112. Scope: SentryReact.Scope,
  113. Severity: SentryReact.Severity,
  114. withProfiler: SentryReact.withProfiler,
  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. const routerFixtures = {
  133. router: (params = {}): InjectedRouter => ({
  134. push: jest.fn(),
  135. replace: jest.fn(),
  136. go: jest.fn(),
  137. goBack: jest.fn(),
  138. goForward: jest.fn(),
  139. setRouteLeaveHook: jest.fn(),
  140. isActive: jest.fn(),
  141. createHref: jest.fn().mockImplementation(to => {
  142. if (typeof to === 'string') {
  143. return to;
  144. }
  145. if (typeof to === 'object') {
  146. if (!to.query) {
  147. return to.pathname;
  148. }
  149. return `${to.pathname}?${stringify(to.query)}`;
  150. }
  151. return '';
  152. }),
  153. location: routerFixtures.location(),
  154. createPath: jest.fn(),
  155. routes: [],
  156. params: {},
  157. ...params,
  158. }),
  159. location: (params: Partial<Location> = {}): Location => ({
  160. key: '',
  161. search: '',
  162. hash: '',
  163. action: 'PUSH',
  164. state: null,
  165. query: {},
  166. pathname: '/mock-pathname/',
  167. ...params,
  168. }),
  169. routerProps: (params = {}) => ({
  170. location: routerFixtures.location(),
  171. params: {},
  172. routes: [],
  173. stepBack: () => {},
  174. ...params,
  175. }),
  176. routeComponentProps: <RouteParams = {orgId: string; projectId: string}>(
  177. params: Partial<RouteComponentProps<RouteParams, {}>> = {}
  178. ): RouteComponentProps<RouteParams, {}> => {
  179. const router = routerFixtures.router(params);
  180. return {
  181. location: router.location,
  182. params: router.params as RouteParams & {},
  183. routes: router.routes,
  184. route: router.routes[0],
  185. routeParams: router.params,
  186. router,
  187. };
  188. },
  189. routerContext: ([context, childContextTypes] = []) => ({
  190. context: {
  191. location: routerFixtures.location(),
  192. router: routerFixtures.router(),
  193. organization: Organization(),
  194. project: Project(),
  195. ...context,
  196. },
  197. childContextTypes: {
  198. router: propTypesObject,
  199. location: propTypesObject,
  200. organization: propTypesObject,
  201. project: propTypesObject,
  202. ...childContextTypes,
  203. },
  204. }),
  205. };
  206. const jsFixturesDirectory = path.resolve(__dirname, '../../fixtures/js-stubs/');
  207. const fixtures = makeLazyFixtures(jsFixturesDirectory, routerFixtures);
  208. ConfigStore.loadInitialData(fixtures.Config());
  209. /**
  210. * Test Globals
  211. */
  212. declare global {
  213. /**
  214. * Test stubs are automatically loaded from the fixtures/js-stubs
  215. * directory. Use these for setting up test data.
  216. *
  217. * @deprecated Please import test stubs directly and do not use this global.
  218. */
  219. // eslint-disable-next-line no-var
  220. var TestStubs: typeof fixtures;
  221. /**
  222. * Generates a promise that resolves on the next macro-task
  223. */
  224. // eslint-disable-next-line no-var
  225. var tick: () => Promise<void>;
  226. /**
  227. * Used to mock API requests
  228. */
  229. // eslint-disable-next-line no-var
  230. var MockApiClient: typeof Client;
  231. }
  232. // needed by cbor-web for webauthn
  233. window.TextEncoder = TextEncoder;
  234. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  235. window.TestStubs = fixtures;
  236. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  237. window.tick = () => new Promise(resolve => setTimeout(resolve));
  238. window.MockApiClient = jest.requireMock('sentry/api').Client;
  239. window.scrollTo = jest.fn();
  240. // We need to re-define `window.location`, otherwise we can't spyOn certain
  241. // methods as `window.location` is read-only
  242. Object.defineProperty(window, 'location', {
  243. value: {...window.location, assign: jest.fn(), reload: jest.fn(), replace: jest.fn()},
  244. configurable: true,
  245. writable: true,
  246. });
  247. // The JSDOM implementation is too slow
  248. // Especially for dropdowns that try to position themselves
  249. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  250. Object.defineProperty(window, 'getComputedStyle', {
  251. value: (el: HTMLElement) => {
  252. /**
  253. * This is based on the jsdom implementation of getComputedStyle
  254. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  255. *
  256. * It is missing global style parsing and will only return styles applied directly to an element.
  257. * Will not return styles that are global or from emotion
  258. */
  259. const declaration = new CSSStyleDeclaration();
  260. const {style} = el;
  261. Array.prototype.forEach.call(style, (property: string) => {
  262. declaration.setProperty(
  263. property,
  264. style.getPropertyValue(property),
  265. style.getPropertyPriority(property)
  266. );
  267. });
  268. return declaration;
  269. },
  270. configurable: true,
  271. writable: true,
  272. });
  273. window.IntersectionObserver = class IntersectionObserver {
  274. root = null;
  275. rootMargin = '';
  276. thresholds = [];
  277. takeRecords = jest.fn();
  278. constructor() {}
  279. observe() {}
  280. unobserve() {}
  281. disconnect() {}
  282. };