setup.ts 7.8 KB

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