setup.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import {configure} from '@testing-library/react';
  2. import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
  3. import Enzyme from 'enzyme'; // eslint-disable-line no-restricted-imports
  4. import MockDate from 'mockdate';
  5. import PropTypes from 'prop-types';
  6. import ConfigStore from 'app/stores/configStore';
  7. import {loadFixtures} from './sentry-test/loadFixtures';
  8. export * from './sentry-test/select';
  9. // We need this polyfill for testing only because typescript handles it for
  10. // main application
  11. import 'core-js/features/object/from-entries';
  12. /**
  13. * XXX(epurkhiser): Gross hack to fix a bug in jsdom which makes testing of
  14. * framer-motion SVG components fail
  15. *
  16. * See https://github.com/jsdom/jsdom/issues/1330
  17. */
  18. if (!SVGElement.prototype.getTotalLength) {
  19. SVGElement.prototype.getTotalLength = () => 1;
  20. }
  21. /**
  22. * React Testing Library configuration to override the default test id attribute
  23. *
  24. * See: https://testing-library.com/docs/queries/bytestid/#overriding-data-testid
  25. */
  26. configure({testIdAttribute: 'data-test-id'});
  27. /**
  28. * Enzyme configuration
  29. *
  30. * TODO(epurkhiser): We're using @wojtekmaj's react-17 enzyme adapter, until
  31. * the offical adapter has been released.
  32. *
  33. * https://github.com/enzymejs/enzyme/issues/2429
  34. */
  35. Enzyme.configure({adapter: new Adapter()});
  36. /**
  37. * Mock (current) date to always be National Pasta Day
  38. * 2017-10-17T02:41:20.000Z
  39. */
  40. const constantDate = new Date(1508208080000);
  41. MockDate.set(constantDate);
  42. /**
  43. * Load all files in `tests/js/fixtures/*` as a module.
  44. * These will then be added to the `TestStubs` global below
  45. */
  46. const fixtures = loadFixtures('js-stubs', {flatten: true});
  47. /**
  48. * Global testing configuration
  49. */
  50. ConfigStore.loadInitialData({
  51. messages: [],
  52. user: fixtures.User(),
  53. });
  54. /**
  55. * Mocks
  56. */
  57. jest.mock('lodash/debounce', () => jest.fn(fn => fn));
  58. jest.mock('app/utils/recreateRoute');
  59. jest.mock('app/api');
  60. jest.mock('app/utils/domId');
  61. jest.mock('app/utils/withOrganization');
  62. jest.mock('scroll-to-element', () => jest.fn());
  63. jest.mock('react-router', () => {
  64. const ReactRouter = jest.requireActual('react-router');
  65. return {
  66. IndexRedirect: ReactRouter.IndexRedirect,
  67. IndexRoute: ReactRouter.IndexRoute,
  68. Link: ReactRouter.Link,
  69. Redirect: ReactRouter.Redirect,
  70. Route: ReactRouter.Route,
  71. withRouter: ReactRouter.withRouter,
  72. browserHistory: {
  73. goBack: jest.fn(),
  74. push: jest.fn(),
  75. replace: jest.fn(),
  76. listen: jest.fn(() => {}),
  77. },
  78. };
  79. });
  80. jest.mock('react-lazyload', () => {
  81. const LazyLoadMock = ({children}) => children;
  82. return LazyLoadMock;
  83. });
  84. jest.mock('react-virtualized', () => {
  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', () => {
  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', () => {
  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. startTransaction: () => ({
  125. finish: jest.fn(),
  126. setTag: jest.fn(),
  127. setData: jest.fn(),
  128. setStatus: jest.fn(),
  129. }),
  130. };
  131. });
  132. jest.mock('popper.js', () => {
  133. const PopperJS = jest.requireActual('popper.js');
  134. return class {
  135. static placements = PopperJS.placements;
  136. constructor() {
  137. return {
  138. destroy: () => {},
  139. scheduleUpdate: () => {},
  140. };
  141. }
  142. };
  143. });
  144. /**
  145. * Test Globals
  146. */
  147. // This is so we can use async/await in tests instead of wrapping with `setTimeout`.
  148. window.tick = () => new Promise(resolve => setTimeout(resolve));
  149. window.scrollTo = jest.fn();
  150. // This is very commonly used, so expose it globally.
  151. window.MockApiClient = jest.requireMock('app/api').Client;
  152. window.TestStubs = {
  153. // react-router's 'router' context
  154. router: (params = {}) => ({
  155. push: jest.fn(),
  156. replace: jest.fn(),
  157. go: jest.fn(),
  158. goBack: jest.fn(),
  159. goForward: jest.fn(),
  160. listen: jest.fn(),
  161. setRouteLeaveHook: jest.fn(),
  162. isActive: jest.fn(),
  163. createHref: jest.fn(),
  164. location: {query: {}},
  165. ...params,
  166. }),
  167. location: (params = {}) => ({
  168. query: {},
  169. pathname: '/mock-pathname/',
  170. ...params,
  171. }),
  172. routes: () => [
  173. {path: '/'},
  174. {path: '/:orgId/'},
  175. {name: 'this should be skipped'},
  176. {path: '/organizations/:orgId/'},
  177. {path: 'api-keys/', name: 'API Key'},
  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: fixtures.Organization(),
  191. project: fixtures.Project(),
  192. ...context,
  193. },
  194. childContextTypes: {
  195. router: PropTypes.object,
  196. location: PropTypes.object,
  197. organization: PropTypes.object,
  198. project: PropTypes.object,
  199. ...childContextTypes,
  200. },
  201. }),
  202. AllAuthenticators: () => Object.values(fixtures.Authenticators()).map(x => x()),
  203. ...fixtures,
  204. };
  205. // We now need to re-define `window.location`, otherwise we can't spyOn certain methods
  206. // as `window.location` is read-only
  207. Object.defineProperty(window, 'location', {
  208. value: {...window.location, assign: jest.fn(), reload: jest.fn()},
  209. configurable: true,
  210. writable: true,
  211. });