setup.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. // 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('react-virtualized', function reactVirtualizedMockFactory() {
  71. const ActualReactVirtualized = jest.requireActual('react-virtualized');
  72. return {
  73. ...ActualReactVirtualized,
  74. AutoSizer: ({children}) => children({width: 100, height: 100}),
  75. };
  76. });
  77. jest.mock('echarts-for-react/lib/core', function echartsMockFactory() {
  78. // We need to do this because `jest.mock` gets hoisted by babel and `React` is not
  79. // guaranteed to be in scope
  80. const ReactActual = require('react');
  81. // We need a class component here because `BaseChart` passes `ref` which will
  82. // error if we return a stateless/functional component
  83. return class extends ReactActual.Component {
  84. render() {
  85. return null;
  86. }
  87. };
  88. });
  89. jest.mock('@sentry/react', function sentryReact() {
  90. const SentryReact = jest.requireActual('@sentry/react');
  91. return {
  92. init: jest.fn(),
  93. configureScope: jest.fn(),
  94. setTag: jest.fn(),
  95. setTags: jest.fn(),
  96. setExtra: jest.fn(),
  97. setExtras: jest.fn(),
  98. captureBreadcrumb: jest.fn(),
  99. addBreadcrumb: jest.fn(),
  100. captureMessage: jest.fn(),
  101. captureException: jest.fn(),
  102. showReportDialog: jest.fn(),
  103. startSpan: jest.fn(),
  104. finishSpan: jest.fn(),
  105. lastEventId: jest.fn(),
  106. getCurrentHub: jest.spyOn(SentryReact, 'getCurrentHub'),
  107. withScope: jest.spyOn(SentryReact, 'withScope'),
  108. Hub: SentryReact.Hub,
  109. Scope: SentryReact.Scope,
  110. Severity: SentryReact.Severity,
  111. withProfiler: SentryReact.withProfiler,
  112. BrowserTracing: jest.fn().mockReturnValue({}),
  113. BrowserProfilingIntegration: jest.fn().mockReturnValue({}),
  114. addGlobalEventProcessor: jest.fn(),
  115. BrowserClient: jest.fn().mockReturnValue({
  116. captureEvent: jest.fn(),
  117. }),
  118. startTransaction: () => ({
  119. finish: jest.fn(),
  120. setTag: jest.fn(),
  121. setData: jest.fn(),
  122. setStatus: jest.fn(),
  123. startChild: jest.fn().mockReturnValue({
  124. finish: jest.fn(),
  125. }),
  126. }),
  127. };
  128. });
  129. const routerFixtures = {
  130. router: (params = {}): InjectedRouter => ({
  131. push: jest.fn(),
  132. replace: jest.fn(),
  133. go: jest.fn(),
  134. goBack: jest.fn(),
  135. goForward: jest.fn(),
  136. setRouteLeaveHook: jest.fn(),
  137. isActive: jest.fn(),
  138. createHref: jest.fn().mockImplementation(to => {
  139. if (typeof to === 'string') {
  140. return to;
  141. }
  142. if (typeof to === 'object') {
  143. if (!to.query) {
  144. return to.pathname;
  145. }
  146. return `${to.pathname}?${stringify(to.query)}`;
  147. }
  148. return '';
  149. }),
  150. location: TestStubs.location(),
  151. createPath: jest.fn(),
  152. routes: [],
  153. params: {},
  154. ...params,
  155. }),
  156. location: (params: Partial<Location> = {}): Location => ({
  157. key: '',
  158. search: '',
  159. hash: '',
  160. action: 'PUSH',
  161. state: null,
  162. query: {},
  163. pathname: '/mock-pathname/',
  164. ...params,
  165. }),
  166. routerProps: (params = {}) => ({
  167. location: TestStubs.location(),
  168. params: {},
  169. routes: [],
  170. stepBack: () => {},
  171. ...params,
  172. }),
  173. routeComponentProps: <RouteParams = {orgId: string; projectId: string}>(
  174. params: Partial<RouteComponentProps<RouteParams, {}>> = {}
  175. ): RouteComponentProps<RouteParams, {}> => {
  176. const router = TestStubs.router(params);
  177. return {
  178. location: router.location,
  179. params: router.params as RouteParams & {},
  180. routes: router.routes,
  181. route: router.routes[0],
  182. routeParams: router.params,
  183. router,
  184. };
  185. },
  186. routerContext: ([context, childContextTypes] = []) => ({
  187. context: {
  188. location: TestStubs.location(),
  189. router: TestStubs.router(),
  190. organization: TestStubs.Organization(),
  191. project: TestStubs.Project(),
  192. ...context,
  193. },
  194. childContextTypes: {
  195. router: propTypesObject,
  196. location: propTypesObject,
  197. organization: propTypesObject,
  198. project: propTypesObject,
  199. ...childContextTypes,
  200. },
  201. }),
  202. };
  203. const jsFixturesDirectory = path.resolve(__dirname, '../../fixtures/js-stubs/');
  204. const fixtures = makeLazyFixtures(jsFixturesDirectory, routerFixtures);
  205. ConfigStore.loadInitialData(fixtures.Config());
  206. /**
  207. * Test Globals
  208. */
  209. declare global {
  210. /**
  211. * Test stubs are automatically loaded from the fixtures/js-stubs
  212. * directory. Use these for setting up test data.
  213. *
  214. * @deprecated Please import test stubs directly and do not use this global.
  215. */
  216. // eslint-disable-next-line no-var
  217. var TestStubs: typeof fixtures;
  218. /**
  219. * Generates a promise that resolves on the next macro-task
  220. */
  221. // eslint-disable-next-line no-var
  222. var tick: () => Promise<void>;
  223. /**
  224. * Used to mock API requests
  225. */
  226. // eslint-disable-next-line no-var
  227. var MockApiClient: typeof Client;
  228. }
  229. // needed by cbor-web for webauthn
  230. window.TextEncoder = TextEncoder;
  231. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  232. window.TestStubs = fixtures;
  233. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  234. window.tick = () => new Promise(resolve => setTimeout(resolve));
  235. window.MockApiClient = jest.requireMock('sentry/api').Client;
  236. window.scrollTo = jest.fn();
  237. // We need to re-define `window.location`, otherwise we can't spyOn certain
  238. // methods as `window.location` is read-only
  239. Object.defineProperty(window, 'location', {
  240. value: {...window.location, assign: jest.fn(), reload: jest.fn(), replace: jest.fn()},
  241. configurable: true,
  242. writable: true,
  243. });
  244. // The JSDOM implementation is too slow
  245. // Especially for dropdowns that try to position themselves
  246. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  247. Object.defineProperty(window, 'getComputedStyle', {
  248. value: (el: HTMLElement) => {
  249. /**
  250. * This is based on the jsdom implementation of getComputedStyle
  251. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  252. *
  253. * It is missing global style parsing and will only return styles applied directly to an element.
  254. * Will not return styles that are global or from emotion
  255. */
  256. const declaration = new CSSStyleDeclaration();
  257. const {style} = el;
  258. Array.prototype.forEach.call(style, (property: string) => {
  259. declaration.setProperty(
  260. property,
  261. style.getPropertyValue(property),
  262. style.getPropertyPriority(property)
  263. );
  264. });
  265. return declaration;
  266. },
  267. configurable: true,
  268. writable: true,
  269. });
  270. window.IntersectionObserver = class IntersectionObserver {
  271. root = null;
  272. rootMargin = '';
  273. thresholds = [];
  274. takeRecords = jest.fn();
  275. constructor() {}
  276. observe() {}
  277. unobserve() {}
  278. disconnect() {}
  279. };