setup.ts 7.6 KB

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