setup.ts 7.8 KB

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