setup.ts 7.9 KB

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