diff --git a/develop-docs/frontend/using-rtl.mdx b/develop-docs/frontend/using-rtl.mdx index d1fb4bf0588c33..d4803681c02ce5 100644 --- a/develop-docs/frontend/using-rtl.mdx +++ b/develop-docs/frontend/using-rtl.mdx @@ -32,6 +32,22 @@ const organization = OrganizationFixture({access: ['org:admin'], features: ['my- render(, {organization}); ``` +### Add extra providers + +If your component needs more context, pass an `additionalWrapper` to `render()` to compose extra providers inside our default test providers. + +```tsx +import {render, screen} from "sentry-test/reactTestingLibrary"; + +function MyExtraProviders({children}: {children: React.ReactNode}) { + return {children}; +} + +render(, {additionalWrapper: MyExtraProviders}); + +expect(screen.getByText(/example/i)).toBeInTheDocument(); +``` + ## Testing route changes When using `render()`, an in-memory router is used, which will react to navigations with `useNavigate()` or interations with `Link` components. If your component relies on the URL, you can define the initial state in `initialRouterConfig`. You can access the current router state by referencing the returned `router` class, as well as navigate programmatically with `router.navigate()`. @@ -221,3 +237,55 @@ import {render, screen, userEvent} from "sentry-test/reactTestingLibrary"; render(); userEvent.type(screen.getByLabelText("Search by name"), "sentry"); ``` + +## Testing hooks with providers + +Use `renderHookWithProviders()` to test hooks with the same built-in providers as `render()` (organization, theme, query client, and an in-memory router). It returns the regular `renderHook` result plus a `router` helper you can use to inspect location and navigate. + +Set the initial URL and define route patterns via `initialRouterConfig` (use `route` for a single route or `routes` for multiple): + +```tsx +import {useParams} from 'react-router-dom'; +import {renderHookWithProviders, waitFor} from 'sentry-test/reactTestingLibrary'; + +function useRouteId() { + const {id} = useParams(); + return id; +} + +const {result, router} = renderHookWithProviders(useRouteId, { + initialRouterConfig: { + location: {pathname: '/foo/123/'}, + route: '/foo/:id/', + }, +}); + +expect(result.current).toBe('123'); + +// Navigate programmatically +router.navigate('/foo/456/'); + +await waitFor(() => expect(result.current).toBe('456')); +``` + +You can also provide additional providers or override the default organization via options: + +```tsx +import {OrganizationFixture} from 'sentry-fixture/organization'; +import {renderHookWithProviders} from 'sentry-test/reactTestingLibrary'; + +function useFeatureFlag() { + // implementation under test +} + +function MyExtraProviders({children}: {children: React.ReactNode}) { + return {children}; +} + +const organization = OrganizationFixture({features: ['my-feature-flag']}); + +const {result} = renderHookWithProviders(useFeatureFlag, { + organization, + additionalWrapper: MyExtraProviders, +}); +```