reactTestingLibrary.tsx 4.8 KB

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