reactTestingLibrary.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import {type RouteObject, RouterProvider, type To, useRouteError} from 'react-router-dom';
  2. import {cache} from '@emotion/css'; // eslint-disable-line @emotion/no-vanilla
  3. import {CacheProvider, ThemeProvider} from '@emotion/react';
  4. import {
  5. createMemoryHistory,
  6. createRouter,
  7. type InitialEntry,
  8. type MemoryHistory,
  9. type Router,
  10. type RouterNavigateOptions,
  11. } from '@remix-run/router';
  12. import * as rtl from '@testing-library/react'; // eslint-disable-line no-restricted-imports
  13. import userEvent from '@testing-library/user-event'; // eslint-disable-line no-restricted-imports
  14. import * as qs from 'query-string';
  15. import {LocationFixture} from 'sentry-fixture/locationFixture';
  16. import {makeTestQueryClient} from 'sentry-test/queryClient';
  17. import {GlobalDrawer} from 'sentry/components/globalDrawer';
  18. import GlobalModal from 'sentry/components/globalModal';
  19. import type {InjectedRouter} from 'sentry/types/legacyReactRouter';
  20. import type {Organization} from 'sentry/types/organization';
  21. import {DANGEROUS_SET_TEST_HISTORY} from 'sentry/utils/browserHistory';
  22. import {ProvideAriaRouter} from 'sentry/utils/provideAriaRouter';
  23. import {QueryClientProvider} from 'sentry/utils/queryClient';
  24. import {lightTheme} from 'sentry/utils/theme';
  25. import {OrganizationContext} from 'sentry/views/organizationContext';
  26. import {TestRouteContext} from 'sentry/views/routeContext';
  27. import {instrumentUserEvent} from '../instrumentedEnv/userEventIntegration';
  28. import {initializeOrg} from './initializeOrg';
  29. interface ProviderOptions {
  30. /**
  31. * Do not shim the router use{Routes,Router,Navigate,Location} functions, and
  32. * instead allow them to work as normal, rendering inside of a memory router.
  33. *
  34. * When enabling this passing a `router` object *will do nothing*!
  35. */
  36. disableRouterMocks?: boolean;
  37. /**
  38. * Sets the history for the router.
  39. */
  40. history?: MemoryHistory;
  41. /**
  42. * Sets the OrganizationContext. You may pass null to provide no organization
  43. */
  44. organization?: Partial<Organization> | null;
  45. /**
  46. * Sets the RouterContext.
  47. */
  48. router?: Partial<InjectedRouter>;
  49. }
  50. interface BaseRenderOptions<T extends boolean = boolean>
  51. extends Omit<ProviderOptions, 'history' | 'disableRouterMocks'>,
  52. rtl.RenderOptions {
  53. disableRouterMocks?: T;
  54. }
  55. type RouterConfig = {
  56. location: InitialEntry;
  57. };
  58. type RenderOptions<T extends boolean = false> = T extends true
  59. ? BaseRenderOptions<T> & {initialRouterConfig?: RouterConfig}
  60. : BaseRenderOptions<T>;
  61. type RenderReturn<T extends boolean = boolean> = T extends true
  62. ? rtl.RenderResult & {router: TestRouter}
  63. : rtl.RenderResult;
  64. function makeAllTheProviders(options: ProviderOptions) {
  65. const {organization, router} = initializeOrg({
  66. organization: options.organization === null ? undefined : options.organization,
  67. router: options.router,
  68. });
  69. // In some cases we may want to not provide an organization at all
  70. const optionalOrganization = options.organization === null ? null : organization;
  71. return function ({children}: {children?: React.ReactNode}) {
  72. const content = (
  73. <OrganizationContext.Provider value={optionalOrganization}>
  74. <GlobalDrawer>{children}</GlobalDrawer>
  75. </OrganizationContext.Provider>
  76. );
  77. const wrappedContent = options.disableRouterMocks ? (
  78. content
  79. ) : (
  80. <TestRouteContext.Provider
  81. value={{
  82. router,
  83. location: router.location,
  84. params: router.params,
  85. routes: router.routes,
  86. }}
  87. >
  88. {/* ProvideAriaRouter may not be necessary in tests but matches routes.tsx */}
  89. <ProvideAriaRouter>{content}</ProvideAriaRouter>
  90. </TestRouteContext.Provider>
  91. );
  92. const history = options.history ?? createMemoryHistory();
  93. // Inject legacy react-router 3 style router mocked navigation functions
  94. // into the memory history used in react router 6
  95. //
  96. // TODO(epurkhiser): In a world without react-router 3 we should figure out
  97. // how to write our tests in a simpler way without all these shims
  98. if (!options.disableRouterMocks) {
  99. Object.defineProperty(history, 'location', {get: () => router.location});
  100. history.replace = router.replace;
  101. history.push = (path: any) => {
  102. if (typeof path === 'object' && path.search) {
  103. path.query = qs.parse(path.search);
  104. delete path.search;
  105. delete path.hash;
  106. delete path.state;
  107. delete path.key;
  108. }
  109. // XXX(epurkhiser): This is a hack for react-router 3 to 6. react-router
  110. // 6 will not convert objects into strings before pushing. We can detect
  111. // this by looking for an empty hash, which we normally do not set for
  112. // our browserHistory.push calls
  113. if (typeof path === 'object' && path.hash === '') {
  114. const queryString = path.query ? qs.stringify(path.query) : null;
  115. path = `${path.pathname}${queryString ? `?${queryString}` : ''}`;
  116. }
  117. router.push(path);
  118. };
  119. }
  120. DANGEROUS_SET_TEST_HISTORY({
  121. goBack: router.goBack,
  122. push: router.push,
  123. replace: router.replace,
  124. listen: jest.fn(() => {}),
  125. listenBefore: jest.fn(),
  126. getCurrentLocation: jest.fn(() => ({pathname: '', query: {}})),
  127. });
  128. return (
  129. <CacheProvider value={{...cache, compat: true}}>
  130. <ThemeProvider theme={lightTheme}>
  131. <QueryClientProvider client={makeTestQueryClient()}>
  132. {wrappedContent}
  133. </QueryClientProvider>
  134. </ThemeProvider>
  135. </CacheProvider>
  136. );
  137. };
  138. }
  139. function makeRouter({
  140. children,
  141. history,
  142. }: {
  143. history: MemoryHistory;
  144. children?: React.ReactNode;
  145. }) {
  146. // By default react-router 6 catches exceptions and displays the stack
  147. // trace. For tests we want them to bubble out
  148. function ErrorBoundary(): React.ReactNode {
  149. throw useRouteError();
  150. }
  151. const routes: RouteObject[] = [
  152. {
  153. path: '*',
  154. element: children,
  155. errorElement: <ErrorBoundary />,
  156. },
  157. ];
  158. const router = createRouter({
  159. future: {v7_prependBasename: true},
  160. history,
  161. routes,
  162. }).initialize();
  163. return router;
  164. }
  165. class TestRouter {
  166. private router: Router;
  167. constructor(router: Router) {
  168. this.router = router;
  169. }
  170. get location() {
  171. return this.router.state.location;
  172. }
  173. navigate = (to: To | number, opts?: RouterNavigateOptions) => {
  174. rtl.act(() => {
  175. if (typeof to === 'number') {
  176. this.router.navigate(to);
  177. } else {
  178. this.router.navigate(to, opts);
  179. }
  180. });
  181. };
  182. }
  183. /**
  184. * Try avoiding unnecessary context and just mount your component. If it works,
  185. * then you dont need anything else.
  186. *
  187. * render(<TestedComponent />);
  188. *
  189. * If your component requires additional context you can pass it in the
  190. * options.
  191. *
  192. * To test route changes, pass `disableRouterMocks: true`. This will return a
  193. * `router` property which can be used to access the location or manually
  194. * navigate to a route. To set the initial location with mocks disabled,
  195. * pass an `initialRouterConfig`.
  196. */
  197. function render<T extends boolean = false>(
  198. ui: React.ReactElement,
  199. options: RenderOptions<T> = {} as RenderOptions<T>
  200. ): RenderReturn<T> {
  201. const initialEntry =
  202. (options.disableRouterMocks
  203. ? options.initialRouterConfig?.location
  204. : options.router?.location?.pathname) ?? LocationFixture().pathname;
  205. const history = createMemoryHistory({
  206. initialEntries: [initialEntry],
  207. });
  208. const AllTheProviders = makeAllTheProviders({
  209. organization: options.organization,
  210. router: options.router,
  211. disableRouterMocks: options.disableRouterMocks,
  212. history,
  213. });
  214. const memoryRouter = makeRouter({
  215. children: <AllTheProviders>{ui}</AllTheProviders>,
  216. history,
  217. });
  218. const renderResult = rtl.render(<RouterProvider router={memoryRouter} />, options);
  219. const rerender = (newUi: React.ReactElement) => {
  220. const newRouter = makeRouter({
  221. children: <AllTheProviders>{newUi}</AllTheProviders>,
  222. history,
  223. });
  224. renderResult.rerender(<RouterProvider router={newRouter} />);
  225. };
  226. const testRouter = new TestRouter(memoryRouter);
  227. return {
  228. ...renderResult,
  229. rerender,
  230. ...(options.disableRouterMocks ? {router: testRouter} : {}),
  231. } as RenderReturn<T>;
  232. }
  233. /**
  234. * @deprecated
  235. * Use userEvent over fireEvent where possible.
  236. * More details: https://kentcdodds.com/blog/common-mistakes-with-react-testing-library#not-using-testing-libraryuser-event
  237. */
  238. const fireEvent = rtl.fireEvent;
  239. function renderGlobalModal(options?: BaseRenderOptions) {
  240. const result = render(<GlobalModal />, options);
  241. /**
  242. * Helper that waits for the modal to be removed from the DOM. You may need to
  243. * wait for the modal to be removed to avoid any act warnings.
  244. */
  245. function waitForModalToHide() {
  246. return rtl.waitFor(() => {
  247. expect(rtl.screen.queryByRole('dialog')).not.toBeInTheDocument();
  248. });
  249. }
  250. return {...result, waitForModalToHide};
  251. }
  252. /**
  253. * Helper that waits for the drawer to be hidden from the DOM. You may need to
  254. * wait for the drawer to be removed to avoid any act warnings.
  255. */
  256. function waitForDrawerToHide(ariaLabel: string) {
  257. return rtl.waitFor(() => {
  258. expect(
  259. rtl.screen.queryByRole('complementary', {name: ariaLabel})
  260. ).not.toBeInTheDocument();
  261. });
  262. }
  263. /**
  264. * This cannot be implemented as a Sentry Integration because Jest creates an
  265. * isolated environment for each test suite. This means that if we were to apply
  266. * the monkey patching ahead of time, it would be shadowed by Jest.
  267. */
  268. instrumentUserEvent();
  269. // eslint-disable-next-line no-restricted-imports, import/export
  270. export * from '@testing-library/react';
  271. export {
  272. // eslint-disable-next-line import/export
  273. render,
  274. renderGlobalModal,
  275. userEvent,
  276. // eslint-disable-next-line import/export
  277. fireEvent,
  278. waitForDrawerToHide,
  279. makeAllTheProviders,
  280. };