setup.ts 7.5 KB

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