setup.ts 8.7 KB

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