setup.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /* eslint-env node */
  2. /* eslint import/no-nodejs-modules:0 */
  3. import {TextDecoder, TextEncoder} from 'util';
  4. import {InjectedRouter} from 'react-router';
  5. import {configure as configureRtl} from '@testing-library/react'; // eslint-disable-line no-restricted-imports
  6. import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
  7. import {configure as configureEnzyme} from 'enzyme'; // eslint-disable-line no-restricted-imports
  8. import {Config} from 'fixtures/js-stubs/config';
  9. import {location} from 'fixtures/js-stubs/location';
  10. import {Organization} from 'fixtures/js-stubs/organization';
  11. import {Project} from 'fixtures/js-stubs/project';
  12. import {router} from 'fixtures/js-stubs/router';
  13. import {Location} from 'history';
  14. import MockDate from 'mockdate';
  15. import * as PropTypes from 'prop-types';
  16. import * as qs from 'query-string';
  17. // eslint-disable-next-line jest/no-mocks-import
  18. import type {Client} from 'sentry/__mocks__/api';
  19. import ConfigStore from 'sentry/stores/configStore';
  20. import TestStubFixtures from '../../fixtures/js-stubs/types';
  21. // needed by cbor-web for webauthn
  22. window.TextEncoder = TextEncoder;
  23. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  24. /**
  25. * XXX(epurkhiser): Gross hack to fix a bug in jsdom which makes testing of
  26. * framer-motion SVG components fail
  27. *
  28. * See https://github.com/jsdom/jsdom/issues/1330
  29. */
  30. // @ts-expect-error
  31. SVGElement.prototype.getTotalLength ??= () => 1;
  32. /**
  33. * React Testing Library configuration to override the default test id attribute
  34. *
  35. * See: https://testing-library.com/docs/queries/bytestid/#overriding-data-testid
  36. */
  37. configureRtl({testIdAttribute: 'data-test-id'});
  38. /**
  39. * Enzyme configuration
  40. *
  41. * TODO(epurkhiser): We're using @wojtekmaj's react-17 enzyme adapter, until
  42. * the official adapter has been released.
  43. *
  44. * https://github.com/enzymejs/enzyme/issues/2429
  45. */
  46. configureEnzyme({adapter: new Adapter()});
  47. /**
  48. * Mock (current) date to always be National Pasta Day
  49. * 2017-10-17T02:41:20.000Z
  50. */
  51. const constantDate = new Date(1508208080000);
  52. MockDate.set(constantDate);
  53. /**
  54. * Global testing configuration
  55. */
  56. ConfigStore.loadInitialData(Config());
  57. /**
  58. * Mocks
  59. */
  60. jest.mock('lodash/debounce', () => jest.fn(fn => fn));
  61. jest.mock('sentry/utils/recreateRoute');
  62. jest.mock('sentry/api');
  63. jest.mock('sentry/utils/withOrganization');
  64. jest.mock('scroll-to-element', () => jest.fn());
  65. jest.mock('react-router', () => {
  66. const ReactRouter = jest.requireActual('react-router');
  67. return {
  68. ...ReactRouter,
  69. browserHistory: {
  70. goBack: jest.fn(),
  71. push: jest.fn(),
  72. replace: jest.fn(),
  73. listen: jest.fn(() => {}),
  74. },
  75. };
  76. });
  77. jest.mock('react-lazyload', () => {
  78. const LazyLoadMock = ({children}) => children;
  79. return LazyLoadMock;
  80. });
  81. jest.mock('react-virtualized', () => {
  82. const ActualReactVirtualized = jest.requireActual('react-virtualized');
  83. return {
  84. ...ActualReactVirtualized,
  85. AutoSizer: ({children}) => children({width: 100, height: 100}),
  86. };
  87. });
  88. jest.mock('echarts-for-react/lib/core', () => {
  89. // We need to do this because `jest.mock` gets hoisted by babel and `React` is not
  90. // guaranteed to be in scope
  91. const ReactActual = require('react');
  92. // We need a class component here because `BaseChart` passes `ref` which will
  93. // error if we return a stateless/functional component
  94. return class extends ReactActual.Component {
  95. render() {
  96. return null;
  97. }
  98. };
  99. });
  100. jest.mock('@sentry/react', () => {
  101. const SentryReact = jest.requireActual('@sentry/react');
  102. return {
  103. init: jest.fn(),
  104. configureScope: jest.fn(),
  105. setTag: jest.fn(),
  106. setTags: jest.fn(),
  107. setExtra: jest.fn(),
  108. setExtras: jest.fn(),
  109. captureBreadcrumb: jest.fn(),
  110. addBreadcrumb: jest.fn(),
  111. captureMessage: jest.fn(),
  112. captureException: jest.fn(),
  113. showReportDialog: jest.fn(),
  114. startSpan: jest.fn(),
  115. finishSpan: jest.fn(),
  116. lastEventId: jest.fn(),
  117. getCurrentHub: jest.spyOn(SentryReact, 'getCurrentHub'),
  118. withScope: jest.spyOn(SentryReact, 'withScope'),
  119. Severity: SentryReact.Severity,
  120. withProfiler: SentryReact.withProfiler,
  121. BrowserClient: jest.fn().mockReturnValue({
  122. captureEvent: jest.fn(),
  123. }),
  124. startTransaction: () => ({
  125. finish: jest.fn(),
  126. setTag: jest.fn(),
  127. setData: jest.fn(),
  128. setStatus: jest.fn(),
  129. startChild: jest.fn().mockReturnValue({
  130. finish: jest.fn(),
  131. }),
  132. }),
  133. };
  134. });
  135. const routerFixtures = {
  136. router: (params = {}): InjectedRouter => ({
  137. push: jest.fn(),
  138. replace: jest.fn(),
  139. go: jest.fn(),
  140. goBack: jest.fn(),
  141. goForward: jest.fn(),
  142. setRouteLeaveHook: jest.fn(),
  143. isActive: jest.fn(),
  144. createHref: jest.fn().mockImplementation(to => {
  145. if (typeof to === 'string') {
  146. return to;
  147. }
  148. if (typeof to === 'object') {
  149. if (!to.query) {
  150. return to.pathname;
  151. }
  152. return `${to.pathname}?${qs.stringify(to.query)}`;
  153. }
  154. return '';
  155. }),
  156. location: TestStubs.location(),
  157. createPath: jest.fn(),
  158. routes: [],
  159. params: {},
  160. ...params,
  161. }),
  162. location: (params: Partial<Location> = {}): Location => ({
  163. key: '',
  164. search: '',
  165. hash: '',
  166. action: 'PUSH',
  167. state: null,
  168. query: {},
  169. pathname: '/mock-pathname/',
  170. ...params,
  171. }),
  172. routerProps: (params = {}) => ({
  173. location: TestStubs.location(),
  174. params: {},
  175. routes: [],
  176. stepBack: () => {},
  177. ...params,
  178. }),
  179. routerContext: ([context, childContextTypes] = []) => ({
  180. context: {
  181. location: location(),
  182. router: router(),
  183. organization: Organization(),
  184. project: Project(),
  185. ...context,
  186. },
  187. childContextTypes: {
  188. router: PropTypes.object,
  189. location: PropTypes.object,
  190. organization: PropTypes.object,
  191. project: PropTypes.object,
  192. ...childContextTypes,
  193. },
  194. }),
  195. };
  196. type TestStubTypes = TestStubFixtures & typeof routerFixtures;
  197. /**
  198. * Test Globals
  199. */
  200. declare global {
  201. /**
  202. * Test stubs are automatically loaded from the fixtures/js-stubs
  203. * directory. Use these for setting up test data.
  204. */
  205. // eslint-disable-next-line no-var
  206. var TestStubs: TestStubTypes;
  207. /**
  208. * Generates a promise that resolves on the next macro-task
  209. */
  210. // eslint-disable-next-line no-var
  211. var tick: () => Promise<void>;
  212. /**
  213. * Used to mock API requests
  214. */
  215. // eslint-disable-next-line no-var
  216. var MockApiClient: typeof Client;
  217. }
  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()},
  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. });