reactTestingLibrary.tsx 12 KB

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