setup.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. * Enzyme configuration
  31. *
  32. * TODO(epurkhiser): We're using @wojtekmaj's react-17 enzyme adapter, until
  33. * the official adapter has been released.
  34. *
  35. * https://github.com/enzymejs/enzyme/issues/2429
  36. */
  37. // eslint-disable-next-line
  38. const tsxTestsWithEnzyme = [
  39. 'eventsV2/savedQuery/index.spec.tsx',
  40. 'dataScrubbing/modals/edit.spec.tsx',
  41. 'eventsV2/homepage.spec.tsx',
  42. 'performance/table.spec.tsx',
  43. 'projectDebugFiles/index.spec.tsx',
  44. 'eventsV2/resultsChart.spec.tsx',
  45. ];
  46. const testPath = expect.getState().testPath;
  47. const isJSXTest = testPath && testPath.endsWith('.jsx');
  48. if (isJSXTest || (testPath && tsxTestsWithEnzyme.some(e => testPath.endsWith(e)))) {
  49. const EnzymeAdapter = require('@wojtekmaj/enzyme-adapter-react-17');
  50. const enzyme = require('enzyme'); // eslint-disable-line no-restricted-imports
  51. enzyme.configure({adapter: new EnzymeAdapter()});
  52. }
  53. /**
  54. * Mock (current) date to always be National Pasta Day
  55. * 2017-10-17T02:41:20.000Z
  56. */
  57. const constantDate = new Date(1508208080000);
  58. MockDate.set(constantDate);
  59. /**
  60. * Global testing configuration
  61. */
  62. /**
  63. * Mocks
  64. */
  65. jest.mock('lodash/debounce', () => jest.fn(fn => fn));
  66. jest.mock('sentry/utils/recreateRoute');
  67. jest.mock('sentry/api');
  68. jest.mock('sentry/utils/withOrganization');
  69. jest.mock('scroll-to-element', () => jest.fn());
  70. jest.mock('react-router', function reactRouterMockFactory() {
  71. const ReactRouter = jest.requireActual('react-router');
  72. return {
  73. ...ReactRouter,
  74. browserHistory: {
  75. goBack: jest.fn(),
  76. push: jest.fn(),
  77. replace: jest.fn(),
  78. listen: jest.fn(() => {}),
  79. listenBefore: jest.fn(),
  80. getCurrentLocation: jest.fn(() => ({pathname: '', query: {}})),
  81. },
  82. };
  83. });
  84. jest.mock('react-lazyload', function reactLazyLoadMockFactory() {
  85. const LazyLoadMock = ({children}) => children;
  86. return LazyLoadMock;
  87. });
  88. jest.mock('react-virtualized', function reactVirtualizedMockFactory() {
  89. const ActualReactVirtualized = jest.requireActual('react-virtualized');
  90. return {
  91. ...ActualReactVirtualized,
  92. AutoSizer: ({children}) => children({width: 100, height: 100}),
  93. };
  94. });
  95. jest.mock('echarts-for-react/lib/core', function echartsMockFactory() {
  96. // We need to do this because `jest.mock` gets hoisted by babel and `React` is not
  97. // guaranteed to be in scope
  98. const ReactActual = require('react');
  99. // We need a class component here because `BaseChart` passes `ref` which will
  100. // error if we return a stateless/functional component
  101. return class extends ReactActual.Component {
  102. render() {
  103. return null;
  104. }
  105. };
  106. });
  107. jest.mock('@sentry/react', function sentryReact() {
  108. const SentryReact = jest.requireActual('@sentry/react');
  109. return {
  110. init: jest.fn(),
  111. configureScope: jest.fn(),
  112. setTag: jest.fn(),
  113. setTags: jest.fn(),
  114. setExtra: jest.fn(),
  115. setExtras: jest.fn(),
  116. captureBreadcrumb: jest.fn(),
  117. addBreadcrumb: jest.fn(),
  118. captureMessage: jest.fn(),
  119. captureException: jest.fn(),
  120. showReportDialog: jest.fn(),
  121. startSpan: jest.fn(),
  122. finishSpan: jest.fn(),
  123. lastEventId: jest.fn(),
  124. getCurrentHub: jest.spyOn(SentryReact, 'getCurrentHub'),
  125. withScope: jest.spyOn(SentryReact, 'withScope'),
  126. Severity: SentryReact.Severity,
  127. withProfiler: SentryReact.withProfiler,
  128. BrowserClient: jest.fn().mockReturnValue({
  129. captureEvent: jest.fn(),
  130. }),
  131. startTransaction: () => ({
  132. finish: jest.fn(),
  133. setTag: jest.fn(),
  134. setData: jest.fn(),
  135. setStatus: jest.fn(),
  136. startChild: jest.fn().mockReturnValue({
  137. finish: jest.fn(),
  138. }),
  139. }),
  140. };
  141. });
  142. const routerFixtures = {
  143. router: (params = {}): InjectedRouter => ({
  144. push: jest.fn(),
  145. replace: jest.fn(),
  146. go: jest.fn(),
  147. goBack: jest.fn(),
  148. goForward: jest.fn(),
  149. setRouteLeaveHook: jest.fn(),
  150. isActive: jest.fn(),
  151. createHref: jest.fn().mockImplementation(to => {
  152. if (typeof to === 'string') {
  153. return to;
  154. }
  155. if (typeof to === 'object') {
  156. if (!to.query) {
  157. return to.pathname;
  158. }
  159. return `${to.pathname}?${stringify(to.query)}`;
  160. }
  161. return '';
  162. }),
  163. location: TestStubs.location(),
  164. createPath: jest.fn(),
  165. routes: [],
  166. params: {},
  167. ...params,
  168. }),
  169. location: (params: Partial<Location> = {}): Location => ({
  170. key: '',
  171. search: '',
  172. hash: '',
  173. action: 'PUSH',
  174. state: null,
  175. query: {},
  176. pathname: '/mock-pathname/',
  177. ...params,
  178. }),
  179. routerProps: (params = {}) => ({
  180. location: TestStubs.location(),
  181. params: {},
  182. routes: [],
  183. stepBack: () => {},
  184. ...params,
  185. }),
  186. routerContext: ([context, childContextTypes] = []) => ({
  187. context: {
  188. location: TestStubs.location(),
  189. router: TestStubs.router(),
  190. organization: TestStubs.Organization(),
  191. project: TestStubs.Project(),
  192. ...context,
  193. },
  194. childContextTypes: {
  195. router: propTypesObject,
  196. location: propTypesObject,
  197. organization: propTypesObject,
  198. project: propTypesObject,
  199. ...childContextTypes,
  200. },
  201. }),
  202. };
  203. const jsFixturesDirectory = path.resolve(__dirname, '../../fixtures/js-stubs/');
  204. const fixtures = makeLazyFixtures(jsFixturesDirectory, routerFixtures);
  205. ConfigStore.loadInitialData(fixtures.Config());
  206. /**
  207. * Test Globals
  208. */
  209. declare global {
  210. /**
  211. * Test stubs are automatically loaded from the fixtures/js-stubs
  212. * directory. Use these for setting up test data.
  213. */
  214. // eslint-disable-next-line no-var
  215. var TestStubs: typeof fixtures;
  216. /**
  217. * Generates a promise that resolves on the next macro-task
  218. */
  219. // eslint-disable-next-line no-var
  220. var tick: () => Promise<void>;
  221. /**
  222. * Used to mock API requests
  223. */
  224. // eslint-disable-next-line no-var
  225. var MockApiClient: typeof Client;
  226. }
  227. // needed by cbor-web for webauthn
  228. window.TextEncoder = TextEncoder;
  229. window.TextDecoder = TextDecoder as typeof window.TextDecoder;
  230. window.TestStubs = fixtures;
  231. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  232. window.tick = () => new Promise(resolve => setTimeout(resolve));
  233. window.MockApiClient = jest.requireMock('sentry/api').Client;
  234. window.scrollTo = jest.fn();
  235. // We need to re-define `window.location`, otherwise we can't spyOn certain
  236. // methods as `window.location` is read-only
  237. Object.defineProperty(window, 'location', {
  238. value: {...window.location, assign: jest.fn(), reload: jest.fn()},
  239. configurable: true,
  240. writable: true,
  241. });
  242. // The JSDOM implementation is too slow
  243. // Especially for dropdowns that try to position themselves
  244. // perf issue - https://github.com/jsdom/jsdom/issues/3234
  245. Object.defineProperty(window, 'getComputedStyle', {
  246. value: (el: HTMLElement) => {
  247. /**
  248. * This is based on the jsdom implementation of getComputedStyle
  249. * https://github.com/jsdom/jsdom/blob/9dae17bf0ad09042cfccd82e6a9d06d3a615d9f4/lib/jsdom/browser/Window.js#L779-L820
  250. *
  251. * It is missing global style parsing and will only return styles applied directly to an element.
  252. * Will not return styles that are global or from emotion
  253. */
  254. const declaration = new CSSStyleDeclaration();
  255. const {style} = el;
  256. Array.prototype.forEach.call(style, (property: string) => {
  257. declaration.setProperty(
  258. property,
  259. style.getPropertyValue(property),
  260. style.getPropertyPriority(property)
  261. );
  262. });
  263. return declaration;
  264. },
  265. configurable: true,
  266. writable: true,
  267. });