reactTestingLibrary.tsx 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import {Component, Fragment} from 'react';
  2. import {InjectedRouter} from 'react-router';
  3. import {cache} from '@emotion/css'; // eslint-disable-line @emotion/no-vanilla
  4. import {CacheProvider, ThemeProvider} from '@emotion/react';
  5. import * as rtl from '@testing-library/react'; // eslint-disable-line no-restricted-imports
  6. import * as reactHooks from '@testing-library/react-hooks'; // eslint-disable-line no-restricted-imports
  7. import userEvent from '@testing-library/user-event'; // eslint-disable-line no-restricted-imports
  8. import merge from 'lodash/merge';
  9. import GlobalModal from 'sentry/components/globalModal';
  10. import {Organization} from 'sentry/types';
  11. import {
  12. DEFAULT_QUERY_CLIENT_CONFIG,
  13. QueryClient,
  14. QueryClientProvider,
  15. } from 'sentry/utils/queryClient';
  16. import {lightTheme} from 'sentry/utils/theme';
  17. import {OrganizationContext} from 'sentry/views/organizationContext';
  18. import {RouteContext} from 'sentry/views/routeContext';
  19. import {instrumentUserEvent} from '../instrumentedEnv/userEventIntegration';
  20. import {initializeOrg} from './initializeOrg';
  21. type ProviderOptions = {
  22. context?: Record<string, any>;
  23. organization?: Partial<Organization>;
  24. project?: string;
  25. projects?: string[];
  26. router?: Partial<InjectedRouter>;
  27. };
  28. type Options = ProviderOptions & rtl.RenderOptions;
  29. const makeQueryClient = () =>
  30. new QueryClient(
  31. merge({}, DEFAULT_QUERY_CLIENT_CONFIG, {
  32. defaultOptions: {
  33. queries: {
  34. // Disable retries for tests to allow them to fail fast
  35. retry: false,
  36. },
  37. mutations: {
  38. // Disable retries for tests to allow them to fail fast
  39. retry: false,
  40. },
  41. },
  42. // Don't want console output in tests
  43. logger: {
  44. log: () => {},
  45. warn: () => {},
  46. error: () => {},
  47. },
  48. })
  49. );
  50. function createProvider(contextDefs: Record<string, any>) {
  51. return class ContextProvider extends Component {
  52. static childContextTypes = contextDefs.childContextTypes;
  53. getChildContext() {
  54. return contextDefs.context;
  55. }
  56. render() {
  57. return this.props.children;
  58. }
  59. };
  60. }
  61. function makeAllTheProviders({context, ...initializeOrgOptions}: ProviderOptions) {
  62. const ContextProvider = context ? createProvider(context) : Fragment;
  63. const {organization, router} = initializeOrg(initializeOrgOptions as any);
  64. return function ({children}: {children?: React.ReactNode}) {
  65. return (
  66. <ContextProvider>
  67. <CacheProvider value={{...cache, compat: true}}>
  68. <ThemeProvider theme={lightTheme}>
  69. <QueryClientProvider client={makeQueryClient()}>
  70. <RouteContext.Provider
  71. value={{
  72. router,
  73. location: router.location,
  74. params: router.params,
  75. routes: router.routes,
  76. }}
  77. >
  78. <OrganizationContext.Provider value={organization}>
  79. {children}
  80. </OrganizationContext.Provider>
  81. </RouteContext.Provider>
  82. </QueryClientProvider>
  83. </ThemeProvider>
  84. </CacheProvider>
  85. </ContextProvider>
  86. );
  87. };
  88. }
  89. /**
  90. * Migrating from enzyme?
  91. * Try avoiding unnecessary context and just mount your component. If it works, then you dont need anything else.
  92. * render(<TestedComponent />);
  93. *
  94. * If your component requires routerContext or organization to render, pass it via context options argument.
  95. * render(<TestedComponent />, {context: routerContext, organization});
  96. */
  97. function render(ui: React.ReactElement, options?: Options) {
  98. options = options ?? {};
  99. const {context, organization, project, projects, ...otherOptions} = options;
  100. let {router} = options;
  101. if (router === undefined && context?.context?.router) {
  102. router = context.context.router;
  103. }
  104. const AllTheProviders = makeAllTheProviders({
  105. context,
  106. organization,
  107. project,
  108. projects,
  109. router,
  110. });
  111. return rtl.render(ui, {wrapper: AllTheProviders, ...otherOptions});
  112. }
  113. /**
  114. * @deprecated
  115. * Use userEvent over fireEvent where possible.
  116. * More details: https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#not-using-testing-libraryuser-event
  117. */
  118. const fireEvent = rtl.fireEvent;
  119. function renderGlobalModal(options?: Options) {
  120. return render(<GlobalModal />, options);
  121. }
  122. /**
  123. * jest-sentry-environment attaches a global Sentry object that can be used.
  124. * The types on it conflicts with the existing window.Sentry object so it's using any here.
  125. */
  126. const globalSentry = (global as any).Sentry;
  127. /**
  128. * This cannot be implemented as a Sentry Integration because Jest creates an
  129. * isolated environment for each test suite. This means that if we were to apply
  130. * the monkey patching ahead of time, it would be shadowed by Jest.
  131. */
  132. instrumentUserEvent(globalSentry?.getCurrentHub.bind(globalSentry));
  133. // eslint-disable-next-line no-restricted-imports, import/export
  134. export * from '@testing-library/react';
  135. // eslint-disable-next-line import/export
  136. export {render, renderGlobalModal, userEvent, reactHooks, fireEvent};