reactTestingLibrary.tsx 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import {Component} from 'react';
  2. import type {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 type {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. /**
  19. * Sets legacy context providers. This value is directly passed to a
  20. * `getChildContext`.
  21. */
  22. context?: Record<string, any>;
  23. /**
  24. * Sets the OrganizationContext. You may pass null to provide no organization
  25. */
  26. organization?: Partial<Organization> | null;
  27. /**
  28. * Sets the RouterContext
  29. */
  30. router?: Partial<InjectedRouter>;
  31. };
  32. type Options = ProviderOptions & rtl.RenderOptions;
  33. function createProvider(contextDefs: Record<string, any>) {
  34. return class ContextProvider extends Component {
  35. static childContextTypes = contextDefs.childContextTypes;
  36. getChildContext() {
  37. return contextDefs.context;
  38. }
  39. render() {
  40. return this.props.children;
  41. }
  42. };
  43. }
  44. function makeAllTheProviders({context, ...initializeOrgOptions}: ProviderOptions) {
  45. const {organization, router, routerContext} = initializeOrg(
  46. initializeOrgOptions as any
  47. );
  48. const ContextProvider = context
  49. ? createProvider(context)
  50. : createProvider(routerContext);
  51. // In some cases we may want to not provide an organization at all
  52. const optionalOrganization =
  53. initializeOrgOptions.organization === null ? null : organization;
  54. return function ({children}: {children?: React.ReactNode}) {
  55. return (
  56. <ContextProvider>
  57. <CacheProvider value={{...cache, compat: true}}>
  58. <ThemeProvider theme={lightTheme}>
  59. <QueryClientProvider client={makeTestQueryClient()}>
  60. <RouteContext.Provider
  61. value={{
  62. router,
  63. location: router.location,
  64. params: router.params,
  65. routes: router.routes,
  66. }}
  67. >
  68. <OrganizationContext.Provider value={optionalOrganization}>
  69. {children}
  70. </OrganizationContext.Provider>
  71. </RouteContext.Provider>
  72. </QueryClientProvider>
  73. </ThemeProvider>
  74. </CacheProvider>
  75. </ContextProvider>
  76. );
  77. };
  78. }
  79. /**
  80. * Try avoiding unnecessary context and just mount your component. If it works,
  81. * then you dont need anything else.
  82. *
  83. * render(<TestedComponent />);
  84. *
  85. * If your component requires routerContext or organization to render, pass it
  86. * via context options argument. render(<TestedComponent />, {context:
  87. * routerContext, organization});
  88. */
  89. function render(ui: React.ReactElement, options?: Options) {
  90. options = options ?? {};
  91. const {context, organization, ...otherOptions} = options;
  92. let {router} = options;
  93. if (router === undefined && context?.context?.router) {
  94. router = context.context.router;
  95. }
  96. const AllTheProviders = makeAllTheProviders({
  97. context,
  98. organization,
  99. router,
  100. });
  101. return rtl.render(ui, {wrapper: AllTheProviders, ...otherOptions});
  102. }
  103. /**
  104. * @deprecated
  105. * Use userEvent over fireEvent where possible.
  106. * More details: https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#not-using-testing-libraryuser-event
  107. */
  108. const fireEvent = rtl.fireEvent;
  109. function renderGlobalModal(options?: Options) {
  110. const result = render(<GlobalModal />, options);
  111. /**
  112. * Helper that waits for the modal to be removed from the DOM. You may need to
  113. * wait for the modal to be removed to avoid any act warnings.
  114. */
  115. function waitForModalToHide() {
  116. return rtl.waitFor(() => {
  117. expect(rtl.screen.queryByRole('dialog')).not.toBeInTheDocument();
  118. });
  119. }
  120. return {...result, waitForModalToHide};
  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};