setup.ts 6.9 KB

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