reactTestingLibrary.tsx 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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
  25. */
  26. organization?: Partial<Organization>;
  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. return function ({children}: {children?: React.ReactNode}) {
  52. return (
  53. <ContextProvider>
  54. <CacheProvider value={{...cache, compat: true}}>
  55. <ThemeProvider theme={lightTheme}>
  56. <QueryClientProvider client={makeTestQueryClient()}>
  57. <RouteContext.Provider
  58. value={{
  59. router,
  60. location: router.location,
  61. params: router.params,
  62. routes: router.routes,
  63. }}
  64. >
  65. <OrganizationContext.Provider value={organization}>
  66. {children}
  67. </OrganizationContext.Provider>
  68. </RouteContext.Provider>
  69. </QueryClientProvider>
  70. </ThemeProvider>
  71. </CacheProvider>
  72. </ContextProvider>
  73. );
  74. };
  75. }
  76. /**
  77. * Try avoiding unnecessary context and just mount your component. If it works,
  78. * then you dont need anything else.
  79. *
  80. * render(<TestedComponent />);
  81. *
  82. * If your component requires routerContext or organization to render, pass it
  83. * via context options argument. render(<TestedComponent />, {context:
  84. * routerContext, organization});
  85. */
  86. function render(ui: React.ReactElement, options?: Options) {
  87. options = options ?? {};
  88. const {context, organization, ...otherOptions} = options;
  89. let {router} = options;
  90. if (router === undefined && context?.context?.router) {
  91. router = context.context.router;
  92. }
  93. const AllTheProviders = makeAllTheProviders({
  94. context,
  95. organization,
  96. router,
  97. });
  98. return rtl.render(ui, {wrapper: AllTheProviders, ...otherOptions});
  99. }
  100. /**
  101. * @deprecated
  102. * Use userEvent over fireEvent where possible.
  103. * More details: https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#not-using-testing-libraryuser-event
  104. */
  105. const fireEvent = rtl.fireEvent;
  106. function renderGlobalModal(options?: Options) {
  107. const result = render(<GlobalModal />, options);
  108. /**
  109. * Helper that waits for the modal to be removed from the DOM. You may need to
  110. * wait for the modal to be removed to avoid any act warnings.
  111. */
  112. function waitForModalToHide() {
  113. return rtl.waitFor(() => {
  114. expect(rtl.screen.queryByRole('dialog')).not.toBeInTheDocument();
  115. });
  116. }
  117. return {...result, waitForModalToHide};
  118. }
  119. /**
  120. * jest-sentry-environment attaches a global Sentry object that can be used.
  121. * The types on it conflicts with the existing window.Sentry object so it's using any here.
  122. */
  123. const globalSentry = (global as any).Sentry;
  124. /**
  125. * This cannot be implemented as a Sentry Integration because Jest creates an
  126. * isolated environment for each test suite. This means that if we were to apply
  127. * the monkey patching ahead of time, it would be shadowed by Jest.
  128. */
  129. instrumentUserEvent(globalSentry?.getCurrentHub.bind(globalSentry));
  130. // eslint-disable-next-line no-restricted-imports, import/export
  131. export * from '@testing-library/react';
  132. // eslint-disable-next-line import/export
  133. export {render, renderGlobalModal, userEvent, reactHooks, fireEvent};