reactTestingLibrary.tsx 12 KB

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