setup.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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} 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. routerContext: ([context, childContextTypes] = []) => ({
  174. context: {
  175. location: TestStubs.location(),
  176. router: TestStubs.router(),
  177. organization: TestStubs.Organization(),
  178. project: TestStubs.Project(),
  179. ...context,
  180. },
  181. childContextTypes: {
  182. router: propTypesObject,
  183. location: propTypesObject,
  184. organization: propTypesObject,
  185. project: propTypesObject,
  186. ...childContextTypes,
  187. },
  188. }),
  189. };
  190. const jsFixturesDirectory = path.resolve(__dirname, '../../fixtures/js-stubs/');
  191. const fixtures = makeLazyFixtures(jsFixturesDirectory, routerFixtures);
  192. ConfigStore.loadInitialData(fixtures.Config());
  193. /**
  194. * Test Globals
  195. */
  196. declare global {
  197. /**
  198. * Test stubs are automatically loaded from the fixtures/js-stubs
  199. * directory. Use these for setting up test data.
  200. */
  201. // eslint-disable-next-line no-var
  202. var TestStubs: typeof fixtures;
  203. /**
  204. * Generates a promise that resolves on the next macro-task
  205. */
  206. // eslint-disable-next-line no-var
  207. var tick: () => Promise<void>;
  208. /**
  209. * Used to mock API requests
  210. */
  211. // eslint-disable-next-line no-var
  212. var MockApiClient: typeof Client;
  213. }
  214. // needed by cbor-web for webauthn
  215. window.TextEncoder = TextEncoder;
  216. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  217. window.TestStubs = fixtures;
  218. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  219. window.tick = () => new Promise(resolve => setTimeout(resolve));
  220. window.MockApiClient = jest.requireMock('sentry/api').Client;
  221. window.scrollTo = jest.fn();
  222. // We need to re-define `window.location`, otherwise we can't spyOn certain
  223. // methods as `window.location` is read-only
  224. Object.defineProperty(window, 'location', {
  225. value: {...window.location, assign: jest.fn(), reload: jest.fn(), replace: jest.fn()},
  226. configurable: true,
  227. writable: true,
  228. });
  229. // The JSDOM implementation is too slow
  230. // Especially for dropdowns that try to position themselves
  231. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  232. Object.defineProperty(window, 'getComputedStyle', {
  233. value: (el: HTMLElement) => {
  234. /**
  235. * This is based on the jsdom implementation of getComputedStyle
  236. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  237. *
  238. * It is missing global style parsing and will only return styles applied directly to an element.
  239. * Will not return styles that are global or from emotion
  240. */
  241. const declaration = new CSSStyleDeclaration();
  242. const {style} = el;
  243. Array.prototype.forEach.call(style, (property: string) => {
  244. declaration.setProperty(
  245. property,
  246. style.getPropertyValue(property),
  247. style.getPropertyPriority(property)
  248. );
  249. });
  250. return declaration;
  251. },
  252. configurable: true,
  253. writable: true,
  254. });