setup.ts 8.3 KB

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