setup.ts 7.7 KB

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