setup.ts 7.5 KB

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